Select2:从我的第一个选择中获取先前选择的选项值

时间:2019-05-17 00:57:06

标签: php jquery select jquery-select2

我有2个select2下拉列表。

1)进行一些验证,如果在选择1中已经选择了该值,则现在将在选择2中将其禁用。

2)现在,如果用户更改选择1的值,则选择1中的上一个值现在将在选择2中启用

Example

Select 1 = A - selected
           B
           C
Select 2 - A - disabled
           B 
           C 

User changed the value in Select 1

Select 1 - A
           B
           C - selected
Select 2 - A - will now enable.
           B
           C - disabled

问题:如何在选择1中启用第一个选定值的先前值?

jQuery

$(document).on('select2:select', '#warehouse_from', function(e){
        //send ajax request
        var id         = $(this).val(); 
        var val        = $('#warehouse_from option:selected').text();
        $('select#warehouse_to>option[value="'+id+'"]').attr('disabled','disabled');
        getItemsByWarehouse(id);
        e.preventDefault();
        return false;
    });

1 个答案:

答案 0 :(得分:0)

用户与一个select2下拉菜单进行交互后,游戏结束了。该实例无法更改。因此,您可以通过编程将其设置为原始 disabled元素的select属性不会反映...

解决这个问题的技巧是destroy实例并重新实例化它。

查看代码中的注释。

CodePen

$(document).ready(function() {

  // On page load instantiation for both select2
  $('.example').select2();

  // On change handler for the 1st select
  $(document).on('change', '#one', function(e){

    // To avoid too many lookups... Store the second select in a variable
    var two = $("#two");

    // If the selected value in 1st select is ALREADY selected in 2nd select, clear it.
    if( two.val() == $(this).val() ){
      two.val(null);
    }

    // Reset the select2 instance (destroy and re-instantiate),
    // Reset the disabled properties
    // Disable the right option
    two.select2('destroy').select2();
    two.find("option").prop("disabled",false);
    two.find("[value='"+$(this).val()+"']").prop("disabled",true);
  });

});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>

<select class="example" id="one">
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>

<select class="example" id="two">
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
</select>