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

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


No jQuery:

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


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


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