rashmeePrakash rashmeePrakash - 3 months ago 11x
HTML Question

How to push values from a multiple select dropdown to an array?

I am trying to push values into an array from a multiple select dropdown box. I am able to do that but what happens is that they are not pushed into the array in the order i set it up to via splice. It is added in the order it is set up on the select box. For example if i select the options in the order of [467, 341, 344, 657, 677], my array shows [344, 467, 677, 341, 657]. I want the array to show in order I have selected the options.
This is my code:

<select multiple class="yo">
<option value = "344">opt1</option>
<option value = "467">opt2</option>
<option value = "677">opt3</option>
<option value = "341">opt1</option>
<option value = "657">opt1</option>

var optVal = new Array();
var tArray;
$('.yo').each(function() {
var newS = $(this).val();
tArray = newS;
optVal.splice(0, 0, tArray);


Please help!

Here is my Fiddle: https://jsfiddle.net/rprakash/e1xcd2gh/


If you only wanted the values inside the select, disregarding order, you could use:


However, you want them order which is much tricker:

var optVal = [];
var tempVal = [];

$(".yo").change(function() {

    $(".yo option").each(function() {
        var val = $(this).val();
        var tempVal = $(".yo").val();

        if(tempVal.indexOf(val) >= 0 && optVal.indexOf(val) < 0) {
        } else if(tempVal.indexOf(val) < 0 && optVal.indexOf(val) >= 0) {
            optVal.splice(optVal.indexOf(val) , 1);

    console.log("Opt: " + optVal);
  • When values have changed, trigger
  • Iterate through each option and get the value
  • Get all selected values from the select
  • If option is selected and not in optVal then push to optVal
  • If option is not selected and inside optVal then remove from optVal

This will keep them in the order they have been selected.

CodePen: http://codepen.io/theblindprophet/pen/RRrJXG?editors=1010