skip to Main Content

I am using Select2 Jquery plugin. I have to 2 selects tableHeader and tableBody where I can select multiple tags on each.
What I am trying to do is :

  • If I select an option or more in first select it/they will be disabled in the second select and vice versa, the same if I unselect an option from one select it will be enabled in other select.

What I did is :

I created an array selections where I am storing the selected options from first select then I am looping through the options of second select and check if the value exists in the array then disable it.

The logic should be correct I guess. Just couldn’t find out why my options are not disabled. Any suggestions please ?

here is my code with explanation.

$(document).ready(function() { 
    
    // this function to search and show matched input
    function matchCustom(params, data) {

    if ($.trim(params.term) === '') { return data; }

    if (typeof data.text === 'undefined') { return null; }

    if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
      var modifiedData = $.extend({}, data, true);
      modifiedData.text += '';
     return modifiedData; }

    return null; }

  $(".select2").select2({
  matcher: matchCustom
  });

//if you select or unselect option trigger this
$('#tableHeader').change(function() {

    var selections = [];
    // if you select an option then add the value in array
   $('#tableHeader').on('select2:select', function (e) { 
    
      $('#tableHeader option:selected').each(function(){
        if($(this).val())
            selections.push($(this).val());  });
     
     });
     // if you unselect an option then remove from array
   $('#tableHeader').on('select2:unselect', function (e) {
      var unselected = e.params.data.id;
      selections.splice( $.inArray(unselected, selections), 1 );

    }); 
     
      console.log(selections);

     // loop through other select option and check if value exists in array then disable it
     $('#tableBody option').each(function() {
       if(jQuery.inArray($(this).val(), selections) !== -1) {  
       console.log($(this).val());
      $('#tableBody option[value="'+ $(this).val() + '"]').prop('disabled',true); }

      });
      
     

    });
    
    // do the same if you start with second select 
    $('#tableBody').change(function() {

    var selections = [];
    
   $('#tableBody').on('select2:select', function (e) { 
    
      $('#tableBody option:selected').each(function(){
        if($(this).val())
            selections.push($(this).val());  });
     
     });
     
   $('#tableBody').on('select2:unselect', function (e) {
      var unselected = e.params.data.id;
      selections.splice( $.inArray(unselected, selections), 1 );

    }); 
     
      console.log(selections);

     $('#tableHeader option').each(function() {
       if(jQuery.inArray($(this).val(), selections) !== -1) {  
       console.log($(this).val());
      $('#tableHeader option[value="'+ $(this).val() + '"]').prop('disabled',true); }

      });
      
     

    });

});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<span>Table Header</span>
<select id="tableHeader" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">      
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>              
</select>
<br>
<span>Table Body</span>
<select id="tableBody" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">      
<option value="Geo">Geo</option>
<option value="Region">Region</option>
<option value="Country">Country</option>
<option value="Order Numer">Order Numer</option>
<option value="Order Value">Order Value</option>
<option value="Brand">Brand</option>
<option value="Quantity">Quantity</option>
<option value="Price">Price</option>
<option value="Revenue">Revenue</option>
<option value="Currency">Currency</option>
<option value="Created Date">Created Date</option>
<option value="Created By">Created By</option>              
</select>

2

Answers


  1. Just enable and disable on change event of each other, see below snipet

    $(document).ready(function() { 
        
            // this function to search and show matched input
        function matchCustom(params, data) {
    
        if ($.trim(params.term) === '') { return data; }
    
        if (typeof data.text === 'undefined') { return null; }
    
        if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
          var modifiedData = $.extend({}, data, true);
          modifiedData.text += '';
         return modifiedData; }
    
        return null; }
    
      $(".select2").select2({
      matcher: matchCustom
      });
        
        var disableTableBody = function(value){
               $('#tableBody option[value="'+ value +'"]').prop('disabled',true);
        };
        
        var enableTableBody = function(value){
           $('#tableBody option[value="'+ value +'"]').prop('disabled',false);
        };
        
           var disableTableHeader = function(value){
               $('#tableHeader option[value="'+ value +'"]').prop('disabled',true);
        };
        
        var enableTableHeader = function(value){
           $('#tableHeader option[value="'+ value +'"]').prop('disabled',false);
        };
        
        
       $("#tableHeader").change(function(){
    		  	   disableTableBody($(this).val());  
       });
       
       $('#tableHeader').on("select2:unselecting", function(e){
       			enableTableBody($(this).val());
       });
    
       $("#tableBody").change(function(){
    		  	   disableTableHeader($(this).val());  
       });
       
       $('#tableBody').on("select2:unselecting", function(e){
       			enableTableHeader($(this).val());
       });
    
    });
       
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"/>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
    
    <span>Table Header</span>
    <select id="tableHeader" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">      
    <option value="Geo">Geo</option>
    <option value="Region">Region</option>
    <option value="Country">Country</option>
    <option value="Order Numer">Order Numer</option>
    <option value="Order Value">Order Value</option>
    <option value="Brand">Brand</option>
    <option value="Quantity">Quantity</option>
    <option value="Price">Price</option>
    <option value="Revenue">Revenue</option>
    <option value="Currency">Currency</option>
    <option value="Created Date">Created Date</option>
    <option value="Created By">Created By</option>              
    </select>
    <br>
    <span>Table Body</span>
    <select id="tableBody" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">      
    <option value="Geo">Geo</option>
    <option value="Region">Region</option>
    <option value="Country">Country</option>
    <option value="Order Numer">Order Numer</option>
    <option value="Order Value">Order Value</option>
    <option value="Brand">Brand</option>
    <option value="Quantity">Quantity</option>
    <option value="Price">Price</option>
    <option value="Revenue">Revenue</option>
    <option value="Currency">Currency</option>
    <option value="Created Date">Created Date</option>
    <option value="Created By">Created By</option>              
    </select>
    Login or Signup to reply.
  2. Your logic while it’s in the idea right, I think you’re just complicating things for yourself. Just get on each change the values of each select, loop through the other select and disable one by one the ones that have the same value.

    $(document).ready(function() {
    
      // this function to search and show matched input
      function matchCustom(params, data) {
    
        if ($.trim(params.term) === '') {
          return data;
        }
    
        if (typeof data.text === 'undefined') {
          return null;
        }
    
        if (data.text.toUpperCase().indexOf(params.term.toUpperCase()) > -1) {
          var modifiedData = $.extend({}, data, true);
          modifiedData.text += '';
          return modifiedData;
        }
    
        return null;
      }
    
      $(".select2").select2({
        matcher: matchCustom
      });
    
      $('#tableHeader').change(function() {
    
        var tableHeader = $(this).val();
        var tableBody = $("#tableBody")[0];
    
        $.each(tableBody.options, function(i, item) {
          if (tableHeader.includes(item.value)) {
            $(item).prop("disabled", true);
          } else {
            $(item).prop("disabled", false);
          }
        });
    
      });
    
      $('#tableBody').change(function() {
    
        var tableBody = $(this).val();
        var tableHeader = $("#tableHeader")[0];
    
        $.each(tableHeader.options, function(i, item) {
          if (tableBody.includes(item.value)) {
            $(item).prop("disabled", true);
          } else {
            $(item).prop("disabled", false);
          }
        });
    
      });
    
    });
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
    
    <span>Table Header</span>
    <select id="tableHeader" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
      <option value="Geo">Geo</option>
      <option value="Region">Region</option>
      <option value="Country">Country</option>
      <option value="Order Numer">Order Numer</option>
      <option value="Order Value">Order Value</option>
      <option value="Brand">Brand</option>
      <option value="Quantity">Quantity</option>
      <option value="Price">Price</option>
      <option value="Revenue">Revenue</option>
      <option value="Currency">Currency</option>
      <option value="Created Date">Created Date</option>
      <option value="Created By">Created By</option>
    </select>
    <br>
    <span>Table Body</span>
    <select id="tableBody" class="select2 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose">
      <option value="Geo">Geo</option>
      <option value="Region">Region</option>
      <option value="Country">Country</option>
      <option value="Order Numer">Order Numer</option>
      <option value="Order Value">Order Value</option>
      <option value="Brand">Brand</option>
      <option value="Quantity">Quantity</option>
      <option value="Price">Price</option>
      <option value="Revenue">Revenue</option>
      <option value="Currency">Currency</option>
      <option value="Created Date">Created Date</option>
      <option value="Created By">Created By</option>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search