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

后端 未结 13 1775
情书的邮戳
情书的邮戳 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 13:01

    $('#select-meal-type :selected') will contain an array of all of the selected items.

    $('#select-meal-type option:selected').each(function() {
        alert($(this).val());
    });
    

    0 讨论(0)
  • 2020-11-27 13:01

    Works everywhere without jquery:

    var getSelectValues = function (select) {
        var ret = [];
    
        // fast but not universally supported
        if (select.selectedOptions != undefined) {
            for (var i=0; i < select.selectedOptions.length; i++) {
                ret.push(select.selectedOptions[i].value);
            }
    
        // compatible, but can be painfully slow
        } else {
            for (var i=0; i < select.options.length; i++) {
                if (select.options[i].selected) {
                    ret.push(select.options[i].value);
                }
            }
        }
        return ret;
    };
    
    0 讨论(0)
  • 2020-11-27 13:04

    If you need to respond to changes, you can try this:

    document.getElementById('select-meal-type').addEventListener('change', function(e) {
        let values = [].slice.call(e.target.selectedOptions).map(a => a.value));
    })
    

    The [].slice.call(e.target.selectedOptions) is needed because e.target.selectedOptions returns a HTMLCollection, not an Array. That call converts it to Array so that we can then apply the map function, which extract the values.

    0 讨论(0)
  • Unless a question asks for JQuery the question should be first answered in standard javascript as many people do not use JQuery in their sites.

    From RobG How to get all selected values of a multiple select box using JavaScript?:

      function getSelectValues(select) {
      var result = [];
      var options = select && select.options;
      var opt;
    
      for (var i=0, iLen=options.length; i<iLen; i++) {
        opt = options[i];
    
        if (opt.selected) {
          result.push(opt.value || opt.text);
        }
      }
      return result;
    }
    
    0 讨论(0)
  • 2020-11-27 13:09

    Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:

    var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) { 
        return v.value; 
    });
    

    UPDATE (2017-02-14):

    An even more succinct way using ES6/ES2015 (for the browsers that support it):

    const selected = document.querySelectorAll('#select-meal-type option:checked');
    const values = Array.from(selected).map(el => el.value);
    
    0 讨论(0)
  • 提交回复
    热议问题