【问题标题】:Select2 : Get the previous selected option value from my 1st selectSelect2 :从我的第一个选择中获取上一个选择的选项值
【发布时间】:2019-05-17 00:57:06
【问题描述】:

我有 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

问题:如何在select 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;
    });

【问题讨论】:

  • 您应该包含一个可验证的示例 - 因此更鼓励其他人查看。

标签: php jquery select jquery-select2


【解决方案1】:

只要用户与select2 下拉菜单交互...游戏就结束了。无法更改实例。所以disabled 属性您可以通过编程设置为他original select 元素不会反映...

绕过它的诀窍是 destroy 实例并重新实例化它。

查看代码中的 cmets。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-03
    • 2013-01-13
    • 2013-10-09
    • 2020-05-22
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    相关资源
    最近更新 更多