Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the selected values in a multiselect tag in Javascript

Tags:

javascript

I have the following code

function searchFlights() {
    var select1 = document.getElementById("airports-select-1");
    var selected1 = [];
    while(select1.selectedIndex != -1) {
      if(select1.selectedIndex != 0) selected1.push(select1.options[select1.selectedIndex].value); 
      select1.options[select1.selectedIndex].selected = false;
   }

   console.log(selected1);
}

This works right, but as you can see from the code this line:

select1.options[select1.selectedIndex].selected = false;

Is doing a deselecting of the value.

Now, I do not want to deselect the values. If I uncomment that line in the code, the code will run forever.

Is there any more refined and sophisticated solution for retrieving multiple values from a select tag using Javascript?

like image 441
aurora Avatar asked Jul 20 '12 16:07

aurora


3 Answers

Wouldn't this do it:

function searchFlights() {
    var select1 = document.getElementById("airports-select-1");
    var selected1 = [];
    for (var i = 0; i < select1.length; i++) {
        if (select1.options[i].selected) selected1.push(select1.options[i].value);
    }
    console.log(selected1);
}​

function searchFlights() {
    var select1 = document.getElementById("airports-select-1");
    var selected1 = [];
    for (var i = 0; i < select1.length; i++) {
        if (select1.options[i].selected) selected1.push(select1.options[i].value);
    }
    console.log(selected1);
}
<form method="post">
  <select name="Select1" multiple="multiple" size="8" id="airports-select-1" onblur="searchFlights()" ;>
    <option>aaa</option>
    <option>bbb</option>
    <option>ccc</option>
    <option>ddd</option>
    <option>eee</option>
  </select>
</form>

jsFiddle example

like image 66
j08691 Avatar answered Oct 14 '22 03:10

j08691


Update for 2018:

  • If the <select> element contains a selectedOptions property, use that collection. The only browser still in wide circulation that doesn't support this is IE (any version). Edge does support it.

  • If this is not supported, the answer by @j08691 is still correct, but as a performance optimization you can start iterating options at selectedIndex instead of 0. This is the index of the first selected option, or -1 if nothing is selected.

like image 21
Adam Leggett Avatar answered Oct 14 '22 05:10

Adam Leggett


Another approach for those who like a more functional style:

selections = Array.from(selectBox.options).filter(o => o.selected).map(o => o.value)

or

selections = Array.from(selectBox.selectedOptions).map(o => o.value)
like image 27
Ray Toal Avatar answered Oct 14 '22 04:10

Ray Toal