i have a multiple select like the following
<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
$("#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
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?
Advertisement
Answer
You always get the same order of the selected
array because you create it each time you run your onChange
function. 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>