How to get all selected values of a multiple select box?

JavascriptHtmlDrop Down-Menu

Javascript Problem Overview


I have a <select> element with the multiple attribute. How can I get this element's selected values using JavaScript?

Here's what I'm trying:

function loopSelected() { 
    var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
    var selectedArray = new Array();
    var selObj = document.getElementById('slct'); 
    var i;
    var count = 0;
    for (i=0; i<selObj.options.length; i++) { 
        if (selObj.options[i].selected) {
            selectedArray[count] = selObj.options[i].value;
            count++; 
        } 
    } 
    txtSelectedValuesObj.value = selectedArray;
}

Javascript Solutions


Solution 1 - Javascript

No jQuery:

// Return an array of the selected opion values
// select is an HTML select element
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;
}

Quick example:

<select multiple>
  <option>opt 1 text
  <option value="opt 2 value">opt 2 text
</select>
<button onclick="
  var el = document.getElementsByTagName('select')[0];
  alert(getSelectValues(el));
">Show selected values</button>

Solution 2 - Javascript

ES6

[...select.options].filter(option => option.selected).map(option => option.value)

Where select is a reference to the <select> element.

To break it down:

  • [...select.options] takes the Array-like list of options and destructures it so that we can use Array.prototype methods on it (Edit: also consider using Array.from())
  • filter(...) reduces the options to only the ones that are selected
  • map(...) converts the raw <option> elements into their respective values

Solution 3 - Javascript

Check-it Out:

HTML:

<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server"  SelectionMode="Multiple" Width="100px">
	<asp:ListItem Text="Raj" Value="1"></asp:ListItem>
	<asp:ListItem Text="Karan" Value="2"></asp:ListItem>
	<asp:ListItem Text="Riya" Value="3"></asp:ListItem>
	<asp:ListItem Text="Aman" Value="4"></asp:ListItem>
	<asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>

JQUERY:

$("#aSelect").click(function(){
	var selectedValues = [];    
	$("#lstSelect :selected").each(function(){
		selectedValues.push($(this).val()); 
	});
	alert(selectedValues);
	return false;
});

CLICK HERE TO SEE THE DEMO

Solution 4 - Javascript

suppose the multiSelect is the Multiple-Select-Element, just use its selectedOptions Property:

//show all selected options in the console:

for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
  console.log( multiSelect.selectedOptions[i].value);
}

Solution 5 - Javascript

Pretty much the same as already suggested but a bit different. About as much code as jQuery in Vanilla JS:

selected = Array.prototype.filter.apply(
  select.options, [
    function(o) {
      return o.selected;
    }
  ]
);

It seems to be faster than a loop in IE, FF and Safari. I find it interesting that it's slower in Chrome and Opera.

Another approach would be using selectors:

selected = Array.prototype.map.apply(
    select.querySelectorAll('option[selected="selected"]'),
    [function (o) { return o.value; }]
);

Solution 6 - Javascript

Check this:

HTML:

<select id="test" multiple>
<option value="red" selected>Red</option>
<option value="rock" selected>Rock</option>
<option value="sun">Sun</option>
</select>

Javascript one line code

Array.from(document.getElementById("test").options).filter(option => option.selected).map(option => option.value);

Solution 7 - Javascript

Here is an ES6 implementation:

value = Array(...el.options).reduce((acc, option) => {
  if (option.selected === true) {
    acc.push(option.value);
  }
  return acc;
}, []);

Solution 8 - Javascript

Building on Rick Viscomi's answer, try using the HTML Select Element's selectedOptions property:

let txtSelectedValuesObj = document.getElementById('txtSelectedValues');
[...txtSelectedValuesObj.selectedOptions].map(option => option.value);

In detail,

  • selectedOptions returns a list of selected items.
  • Specifically, it returns a read-only HTMLCollection containing HTMLOptionElements.
  • ... is spread syntax. It expands the HTMLCollection's elements.
  • [...] creates a mutable Array object from these elements, giving you an array of HTMLOptionElements.
  • map() replaces each HTMLObjectElement in the array (here called option) with its value (option.value).

Dense, but it seems to work.

Watch out, selectedOptions isn't supported by IE!

Solution 9 - Javascript

You Can try this script

     <!DOCTYPE html>
    <html>
    <script>
    function getMultipleSelectedValue()
    {
      var x=document.getElementById("alpha");
      for (var i = 0; i < x.options.length; i++) {
         if(x.options[i].selected ==true){
              alert(x.options[i].value);
          }
      }
    }
    </script>
    </head>
    <body>
    <select multiple="multiple" id="alpha">
      <option value="a">A</option>
      <option value="b">B</option>
      <option value="c">C</option>
      <option value="d">D</option>
    </select>
    <input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
    </body>
    </html>

Solution 10 - Javascript

You can use [].reduce for a more compact implementation of RobG's approach:

var getSelectedValues =  function(selectElement) {
  return [].reduce.call(selectElement.options, function(result, option) {
    if (option.selected) result.push(option.value);
    return result;
  }, []);
};

Solution 11 - Javascript

My template helper looks like this:

 'submit #update': function(event) {
    event.preventDefault();
	var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
    var array_opts = Object.values(obj_opts);  //convert to array
	var stray = array_opts.map((o)=> o.text ); //to filter your bits: text, value or selected
    //do stuff
}

Solution 12 - Javascript

Same as the earlier answer but using underscore.js.

function getSelectValues(select) {
    return _.map(_.filter(select.options, function(opt) { 
        return opt.selected; }), function(opt) { 
            return opt.value || opt.text; });
}

Solution 13 - Javascript

Here ya go.

const arr = Array.from(el.features.selectedOptions) //get array from selectedOptions property
const list = [] 
arr.forEach(item => list.push(item.value)) //push each item to empty array
console.log(list)

Solution 14 - Javascript

Riot js code

this.GetOpt=()=>{

let opt=this.refs.ni;

this.logger.debug("Options length "+opt.options.length);

for(let i=0;i<=opt.options.length;i++)
{
  if(opt.options[i].selected==true)
    this.logger.debug(opt.options[i].value);
}
};

//**ni** is a name of HTML select option element as follows
//**HTML code**
<select multiple ref="ni">
  <option value="">---Select---</option>
  <option value="Option1 ">Gaming</option>
  <option value="Option2">Photoshoot</option>
</select>

Solution 15 - Javascript

You may use jquery plugin chosen .

<head>
 <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css"
 <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
 <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
 <script>
 		jQuery(document).ready(function(){
			jQuery(".chosen").data("placeholder","Select Frameworks...").chosen();
		});
 </script>
</head>
    
 <body> 
   <label for="Test" class="col-md-3 control label">Test</label>
	  <select class="chosen" style="width:350px" multiple="true">
            <option>Choose...</option>
            <option>Java</option>							
            <option>C++</option>
            <option>Python</option>
	 </select>
 </body>

Solution 16 - Javascript

You can create your own function like this and use it everywhere

Pure JS

/**
* Get values from multiple select input field
* @param {string} selectId - the HTML select id of the select field
**/
function getMultiSelectValues(selectId) {
 // get the options of select field which will be HTMLCollection
 // remember HtmlCollection and not an array. You can always enhance the code by
 // verifying if the provided select is valid or not
  var options = document.getElementById(selectId).options; 
	var values = [];
    
   // since options are HtmlCollection, we convert it into array to use map function on it
	Array.from(options).map(function(option) {
		option.selected ? values.push(option.value) : null
    })

	return values;
}

you can get the same result using jQuery in a single line

$('#select_field_id').val()

and this will return the array of values of well.

Solution 17 - Javascript

Example from [HTMLSelectElement.selectedOptions - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions "HTMLSelectElement.selectedOptions - Web APIs | MDN")

let orderButton = document.getElementById("order");
let itemList = document.getElementById("foods");
let outputBox = document.getElementById("output");

orderButton.addEventListener("click", function() {
  let collection = itemList.selectedOptions;
  let output = "";

  for (let i = 0; i < collection.length; i++) {
    if (output === "") {
      output = "Your order for the following items has been placed: ";
    }
    output += collection[i].label;

    if (i === (collection.length - 2) && (collection.length < 3)) {
      output += " and ";
    } else if (i < (collection.length - 2)) {
      output += ", ";
    } else if (i === (collection.length - 2)) {
      output += ", and ";
    }
  }

  if (output === "") {
    output = "You didn't order anything!";
  }

  outputBox.innerHTML = output;
}, false);

<label for="foods">What do you want to eat?</label><br>
<select id="foods" name="foods" size="7" multiple>
  <option value="1">Burrito</option>
  <option value="2">Cheeseburger</option>
  <option value="3">Double Bacon Burger Supreme</option>
  <option value="4">Pepperoni Pizza</option>
  <option value="5">Taco</option>
</select>
<br>
<button name="order" id="order">
  Order Now
</button>
<p id="output">
</p>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTKVView Question on Stackoverflow
Solution 1 - JavascriptRobGView Answer on Stackoverflow
Solution 2 - JavascriptRick ViscomiView Answer on Stackoverflow
Solution 3 - JavascriptSukhjeevanView Answer on Stackoverflow
Solution 4 - JavascriptKAFFEECKOView Answer on Stackoverflow
Solution 5 - JavascriptuKolkaView Answer on Stackoverflow
Solution 6 - JavascriptKrish KView Answer on Stackoverflow
Solution 7 - JavascriptTo_waveView Answer on Stackoverflow
Solution 8 - JavascriptKevin W MatthewsView Answer on Stackoverflow
Solution 9 - JavascriptPankaj ChauhanView Answer on Stackoverflow
Solution 10 - JavascriptrouanView Answer on Stackoverflow
Solution 11 - JavascriptSteve TaylorView Answer on Stackoverflow
Solution 12 - JavascriptF. P. FreelyView Answer on Stackoverflow
Solution 13 - JavascriptDynamisDevelopmentView Answer on Stackoverflow
Solution 14 - JavascriptNilesh PawarView Answer on Stackoverflow
Solution 15 - JavascriptrashedcsView Answer on Stackoverflow
Solution 16 - JavascriptKoushik DasView Answer on Stackoverflow
Solution 17 - JavascriptOokerView Answer on Stackoverflow