提问者:小点点

jQuery select change event无法获取选项值


我想在一个输入中隐藏多个选择,当我改变我的选择(例如,我选择了最后一个选项,然后选择了第一个选项),我在我的输入中得到相同的顺序。

null

$('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>

null

现在如果我改变例如

(BASTIEN Test1/BASTIEN Test2/BASTIEN test0)

当我运行我的代码时

(BASTIEN Test0/BASTIEN Test1/BASTIEN test2)

这是我的代码工作很好,但当我选择最后一个然后第二个,这里的问题是当我选择第三个,他们不工作,我没有得到我的选项的值在我的var


共2个答案

匿名用户

如果我没理解错的话,这可能会有帮助:

使用click事件直接目标选项并将其按顺序保存在数组中。使用e.target.selected?时,请确保仅对selected进行推送。如果取消选择remove函数将从数组中删除元素。

null

var str = []
$('select#brands option').on("click", function(e) {
  e.target.selected ? str.push(e.target.value) : remove(str, e.target.value);

  console.clear()
  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 test0</option>
  <option value="2">BASTIEN test1</option>
  <option value="3">BASTIEN test2</option>
</select>

匿名用户

就像这样。当您从头开始选择时,选项数组将被重置。

    var str = "";
    $('select').change(function() {
    //alert($(this).find("option").length);
       if($(this).find("option").length < str.split(" ").length){
        str = "";
    }
      // For multiple choice
      str = $(this).find("option:selected").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>