How to get all selected values from <select multiple=multiple>?

后端 未结 13 1772
情书的邮戳
情书的邮戳 2020-11-27 12:25

Seemed odd I couldn\'t find this one already asked, but here it goes!

I have an html as follows:


                        
    
提交评论

  • 2020-11-27 12:54

    If you wanna go the modern way, you can do this:

    const selectedOpts = [...field.options].filter((x) => x.selected);
    

    The ... operator maps iterable (HTMLOptionsCollection) to the array.

    If you're just interested in the values, you can add a map() call:

    const selectedValues = [...field.options]
                         .filter((x) => x.selected)
                         .map((x)=>x.value);
    
    0 讨论(0)
  • 2020-11-27 12:54

    if you want as you expressed with breaks after each value;

    $('#select-meal-type').change(function(){
        var meals = $(this).val();
        var selectedmeals = meals.join(", "); // there is a break after comma
    
        alert (selectedmeals); // just for testing what will be printed
    })
    
    0 讨论(0)
  • 2020-11-27 12:57

    Something like the following would be my choice:

    let selectElement = document.getElementById('categorySelect');
    let selectedOptions = selectedElement.selectedOptions || [].filter.call(selectedElement.options, option => option.selected);
    let selectedValues = [].map.call(selectedOptions, option => option.value);
    

    It's short, it's fast on modern browsers, and we don't care whether it's fast or not on 1% market share browsers.

    Note, selectedOptions has wonky behavior on some browsers from around 5 years ago, so a user agent sniff isn't totally out of line here.

    0 讨论(0)
  • 2020-11-27 12:58

    First, use Array.from to convert the HTMLCollection object to an array.

    let selectElement = document.getElementById('categorySelect')
    let selectedValues = Array.from(selectElement.selectedOptions)
            .map(option => option.value) // make sure you know what '.map' does
    
    // you could also do: selectElement.options
    
    0 讨论(0)
  • 2020-11-27 12:58

    You can use selectedOptions

    var selectedValues = Array.from(document.getElementById('select-meal-type').selectedOptions).map(el=>el.value);
    console.log(selectedValues);
    <select id="select-meal-type" multiple="multiple">
        <option value="1">Breakfast</option>
        <option value="2" selected>Lunch</option>
        <option value="3">Dinner</option>
        <option value="4" selected>Snacks</option>
        <option value="5">Dessert</option>
    </select>

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