我需要在用jQuery的两个select2之间选择更改。
例如:
<select id="fromCity" class="select2">
<option value='THR' selected> Tehran </option>
<option value='LON'> London </option>
</select>
和
<select id="toCity" class="select2">
<option value='THR'> Tehran </option>
<option value='LON' selected> London </option>
</select>
现在,我需要单击 thr-> lon 更改为 lon-> thr
在jQuery中:
$('i[data-change-airport]').on('click', function () {
var fromCity = $('#fromCity').val();
var toCity = $('#toCity').val();
$('#fromCity').select2('val', toCity);
$('#toCity').select2('val', fromCity);
})
但是此代码不起作用。问题在哪里?
$('.select2').on('change', function() {
$('.select2').not(this).val($(this).val());
$('.select2').not(this).val($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="fromCity" class="select2">
<option value='THR' selected> Tehran </option>
<option value='LON'> London </option>
</select> And
<select id="toCity" class="select2">
<option value='THR'> Tehran </option>
<option value='LON' selected> London </option>
</select>
尝试这种方式
如果您使用的是最新版本> 4.0,
然后尝试一下,
$('i[data-change-airport]').on('click', function () {
var fromCity = $('#fromCity').val();
var toCity = $('#toCity').val();
$('#fromCity').val(toCity).trigger("change");
$('#toCity').val(fromCity).trigger("change");
});
尝试一下,应该起作用。
如果仍然不起作用,
您可以尝试另一种替代方案
$('#fromCity').val(toCity).trigger('change.select2');
$('#toCity').val(fromCity).trigger('change.select2');
这应该有效。