jquery - 如何更改 jQuery 中 select2 中的 2 个选择框之间的选定选项元素?

标签 jquery

我需要使用 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>

试试这个方法

关于jquery - 如何更改 jQuery 中 select2 中的 2 个选择框之间的选定选项元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42528989/

相关文章:

javascript - 如何在通过 JavaScript 加载图像时显示微调器

javascript - jQuery 中更快的循环

javascript - 评估不在焦点中的元素

javascript - Disqus 评论与我的页脚重叠

javascript - jQuery Draggable div 位置错位

jquery - 覆盖点击绑定(bind)

jquery - 单击时删除类并添加到另一个元素

jquery - 在文档单击时取消固定 div

javascript - 获取没有公共(public)类Jquery的div的索引

jquery - 将项目附加到下拉菜单 jQuery/Ajax