[英]Select2 : Get the previous selected option value from my 1st select
我有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;
});
一旦用戶與一個select2
下拉菜單交互...游戲結束。 實例無法更改。 因此,您可以以編程方式設置為原始 select
元素的disabled
屬性不會反映...
走動的訣竅是銷毀實例並重新實例化它。
請參閱代碼中的注釋。
$(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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.