Getting the selected values in a multiselect tag in Javascript

前端 未结 3 636
逝去的感伤
逝去的感伤 2021-02-07 09:35

I have the following code

function searchFlights() {
    var select1 = document.getElementById(\"airports-select-1\");
    var selected1 = [];
    while(select1         


        
相关标签:
3条回答
  • 2021-02-07 09:57

    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.

    0 讨论(0)
  • 2021-02-07 10:01

    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)
    
    0 讨论(0)
  • 2021-02-07 10:18

    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>ffffd</option>
        <option>eee</option>
      </select>
    </form>

    jsFiddle example

    0 讨论(0)
提交回复
热议问题