首页 > 解决方案 > jQuery多选更改事件无法按选择顺序获取选项值

问题描述

我想在更改选择时将多个选项存储在隐藏的输入中(例如,我选择最后一个选项,然后选择第一个选项)我输入相同的顺序。

$('select').change(function() {
  var str = "";
  // For multiple choice
  $("select option:selected").each(function() {
    str = $(this).val() + str + " ";
  });
  alert(str);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands[]" multiple="multiple">
  <option value="1">BASTIEN test0</option>
  <option value="2">BASTIEN test1</option>
  <option value="3">BASTIEN test2</option>
</select>

现在如果我改变例如

(BASTIEN 测试1/BASTIEN 测试2/BASTIEN 测试0)

当我运行我的代码时,我得到

(BASTIEN 测试0/BASTIEN 测试1/BASTIEN 测试2)

这是我的代码工作正常但是当我选择最后一个然后是第二个时这里的问题是当我选择第三个时它们不起作用并且我没有在我的 var 中获得我的选项的值

标签: javascriptjquery

解决方案


如果我理解正确,这可能会有所帮助:

使用点击事件直接定位选项并将它们按顺序保存在数组中。与e.target.selected ?您一起确保仅在选定时进行推送。 remove如果取消选择,函数将从数组中删除元素。

var str = []
$('select#brands option').on("click", function(e) {
  let l = $(e.target).parent().find("option:selected").length
  console.clear()

  if (l > 1) {
    e.target.selected ? str.push(e.target.value) : remove(str, e.target.value);
  } else if (l === 1 && str.length != 2) {
    str = [e.target.value]
  } else if (l === 1 && str.length === 2) {
    remove(str, e.target.value)
  } else if (l === 0) {
    str = []
  }

  console.log(str)
});


function remove(str, item) {
  var index = str.indexOf(item);
  if (index !== -1) {
    str.splice(index, 1);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="brands[]" class="chosen selectbrands fixed-width-xl" id="brands" multiple="multiple">
  <option value="1">BASTIEN test1</option>
  <option value="2">BASTIEN test2</option>
  <option value="3">BASTIEN test3</option>
  <option value="4">BASTIEN test4</option>
</select>


推荐阅读