[英]If I selected true value assign to other select option via jQuery
如果對主題感到困惑,對不起。
我的網站上有兩個選擇。 它使用select2插件。
首先選擇:
<select name="" id="">
<option value="one"></option>
<option value="two"></option>
<option value="three"></option>
<option value="four"></option>
<option value="five"></option>
</select>
還有一個:
<select name="" id="">
<option value="other_one"></option>
<option value="other_two"></option>
<option value="other_three"></option>
<option value="other_four"></option>
<option value="other_five"></option>
</select>
他們有邏輯。 如果選中的值為one
,則其他選擇中的值必須為other_one
(並且應禁用其他選項)。 同樣,其他選擇選項將在這種情況下起作用。
我在https://select2.github.io/options.html#adapters和Stackoverflow上進行了研究,是的,我可以將觸發器添加到選擇中,例如打印html或文本,但是我需要使用其他觸發器。
我該怎么做?
<select name="" id="select1">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
<option value="four">four</option>
<option value="five">five</option>
<select name="" id="select2">
<option value="other_one">other_one</option>
<option value="other_two">other_two</option>
<option value="other_three">other_three</option>
<option value="other_four">other_four</option>
<option value="other_five">other_five</option>
</select>
$('select').select2();
$("#select1").change(function()
{
$('#select2 option').prop("disabled",false); // remove disabled on all options - basically do a reset
$('#select2 option:selected').prop("disabled",true); // disable the current selected option
$('#select2').select2().select2('val', "other_" + $(this).val()); // set the value of #select2 by concatenating the value from #select1
$('#select2 option:not(:selected)').prop("disabled",true); // disable all other non-selected options
});
您必須添加更改事件,並根據第一個選擇#select1
選擇的一個來更改第二個選擇#select2
的值。
希望這可以幫助。
$("#select1, #select2").select2(); $("#select1").on('change',function() { $('#select2 option').removeAttr('disabled'); var selected_1_value = $(this).val(); $("#select2").val('other_'+selected_1_value).change(); $("#select2 option:not(:selected)").attr('disabled', 'disabled'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <link href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/> <script src="http://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.js"></script> <select name="" id="select1"> <option value="one">1</option> <option value="two">2</option> <option value="three">3</option> <option value="four">4</option> <option value="five">5</option> </select> <select name="" id="select2"> <option value="other_one">other 1</option> <option value="other_two">other 2</option> <option value="other_three">other 3</option> <option value="other_four">other 4</option> <option value="other_five">other 5</option> </select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.