简体   繁体   English

多个 select get Selected options in order to selected

[英]Multiple select get Selected options in order selected

i have a multiple select like the following我有多个 select 如下

<select name="cars" id="cars" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

that i have implemented chosen plugin on i have an onchange listener that adds selected elements to an array like so我已经实现了选择的插件,我有一个 onchange 侦听器,可以像这样将选定的元素添加到数组中

$("#cars").change(function () {
 
    var selected = [];
    for (var option of document.getElementById('cars').options) {
        if (option.selected) {
            selected.push(option.value);
        }
    }
    console.log(selected);


 
});

however in which ever option i select the items they always end up arranging themselves in the order they are in the multiple select for example by selecting the values Volvo, Audi, Saab in that order results in the following array但是,在哪个选项中,我 select 项目最终总是按照它们在多个 select 中的顺序排列,例如通过选择沃尔沃、奥迪、萨博的值以该顺序产生以下数组

Array [ "Volvo" ]
Array [ "Volvo", "Audi" ]
Array(3) [ "Volvo", "Saab", "Audi" ]

Is there a way that i can add elements in a multiple select to an array in the order which they were selected?有没有一种方法可以按选择的顺序将多个 select 中的元素添加到数组中?

You always get the same order of the selected array because you create it each time you run your onChange function.因为每次运行onChange function 时都会创建selected数组的顺序,因此您始终会获得相同的顺序。 So the solution would be to make it a global variable.所以解决方案是让它成为一个全局变量。 When you do that, your array won't be empty at the second choice tho, so you have to take care of removing items from it.当你这样做时,你的数组在第二个选择时不会是空的,所以你必须注意从中删除项目。 Here's some code这是一些代码

 var selected = []; $("#cars").change(function () { for (var option of document.getElementById('cars').options) { var value = option.value; if (option.selected) { if(selected.indexOf(value) < 0){//we only add element if it's not present in the array selected.push(value); } }else{ if(selected.indexOf(value) >= 0){ //we only remove item if it is present selected.splice(selected.indexOf(value),1) } } } console.log(selected); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select name="cars" id="cars" multiple> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM