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


i trying push values array multiple select dropdown box. able happens not pushed array in order set via splice. added in order set on select box. example if select options in order of [467, 341, 344, 657, 677], array shows [344, 467, 677, 341, 657]. want array show in order have selected options. 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> </select>  var optval = new array();         var tarray;         $('.yo').each(function() {             var news = $(this).val();              tarray = news;             optval.splice(0, 0, tarray);          }); 

please help!

here fiddle: https://jsfiddle.net/rprakash/e1xcd2gh/

if wanted values inside select, disregarding order, use:

$(".yo").val() 

however, want them order 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) {             optval.push(val);         } 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 , value
  • get selected values select
  • if option selected , not in optval push optval
  • if option not selected , inside optval remove optval

this keep them in order have been selected.

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


Comments