Как отключить несколько опций для выбора на основе другого выбора в JavaScript / Jquery - PullRequest
3 голосов
/ 09 марта 2020

Я использую плагин Select2 Jquery. У меня есть 2 выбора tableHeader и tableBody , где я могу выбрать несколько тегов для каждого. То, что я пытаюсь сделать, это:

  • Если я выберу опцию или больше в первом, выберите ее / они будут отключены во втором выборе и наоборот, то же самое, если я отменил выбор опции из одного выберите, это будет включено в другом выборе.

То, что я сделал:

Я создал массив выборки , где я сохраняю выбранные опции из первого выбора затем я перебираю опции второго выбора и проверяю, существует ли значение в массиве, затем отключаю его.

Лог c должен быть правильным, я думаю. Просто не мог узнать, почему мои параметры не отключены. Любые предложения, пожалуйста?

вот мой код с объяснением.

$(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/select2@4.0.13/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/select2@4.0.13/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 ]

2 голосов
/ 10 марта 2020

Ваша логика c, хотя она в идеале, я думаю, вы просто усложняете себе жизнь. Просто включите при каждом изменении значения каждого выбора, l oop через другой выбор и отключите один за другим те, которые имеют то же значение.

$(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/select2@4.0.13/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/select2@4.0.13/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>
0 голосов
/ 09 марта 2020

Просто включите и отключите при изменении события друг друга, см. Ниже фрагмент

$(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/select2@4.0.13/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/select2@4.0.13/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>
...