[jquery] How to get multiple select box values using jQuery?

How to get multiple select box values using jQuery?

This question is related to jquery multi-select

The answer is


You can also use js map function:

$("#multipleSelect :selected").map(function(i, el) {
    return $(el).val();
}).get();

And then you can get any property of the option element:

return $(el).text();
return $(el).data("mydata");
return $(el).prop("disabled");
etc...

var selected=[];
 $('#multipleSelect :selected').each(function(){
     selected[$(this).val()]=$(this).text();
    });
console.log(selected);

Yet another approch to this problem. The selected array will have the indexes as the option values and the each array item will have the text as its value.

for example

<select id="multipleSelect" multiple="multiple">
    <option value="abc">Text 1</option>
    <option value="def">Text 2</option>
    <option value="ghi">Text 3</option>
</select>

if say option 1 and 2 are selected.

the selected array will be :

selected['abc']=1; 
selected['def']=2.

Html Code:

 <select id="multiple" multiple="multiple" name="multiple">
  <option value=""> -- Select -- </option>
  <option value="1">Opt1</option>
  <option value="2">Opt2</option>
  <option value="3">Opt3</option>
  <option value="4">Opt4</option>
  <option value="5">Opt5</option>
 </select>   

JQuery Code:

$('#multiple :selected').each(function(i, sel){ 
    alert( $(sel).val() ); 

});

Hope it works


Just use this

$('#multipleSelect').change(function() {
    var selectedValues = $(this).val();  
});

Get selected values in comma separator

var Accessids = "";
$(".multi_select .btn-group>ul>li input:checked").each(function(i,obj)
{
    Accessids=Accessids+$(obj).val()+",";
});
Accessids = Accessids.substring(0,Accessids.length - 1);
console.log(Accessids);

Using the .val() function on a multi-select list will return an array of the selected values:

var selectedValues = $('#multipleSelect').val();

and in your html:

<select id="multipleSelect" multiple="multiple">
    <option value="1">Text 1</option>
    <option value="2">Text 2</option>
    <option value="3">Text 3</option>
</select>

Just by one line-

var select_button_text = $('#SelectQButton option:selected')
                .toArray().map(item => item.text);

Output: ["text1", "text2"]

var select_button_text = $('#SelectQButton option:selected')
                .toArray().map(item => item.value);

Output: ["value1", "value2"]

If you use .join()

var select_button_text = $('#SelectQButton option:selected')
                .toArray().map(item => item.text).join();

Output: text1,text2,text3