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

Kyle picture Kyle · Aug 6, 2012 · Viewed 215.6k times · Source

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

I have an html as follows:

<select id="select-meal-type" multiple="multiple">
    <option value="1">Breakfast</option>
    <option value="2">Lunch</option>
    <option value="3">Dinner</option>
    <option value="4">Snacks</option>
    <option value="5">Dessert</option>
</select>

How do I get all the values(an array?) that the user has selected in javascript?

For example, if the user has selected Lunch and Snacks, I want an array of { 2, 4 }.

This seems like it should be a very simple task but I can't seem to do it.

Thanks.

Answer

lvoelk picture lvoelk · Jan 5, 2015

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;
}