Get value of multiselect box using jQuery or pure JS
var data=[];
var $el=$("#my-select");
$el.find('option:selected').each(function(){
data.push({value:$(this).val(),text:$(this).text()});
});
console.log(data)
I think the answer may be easier to understand like this:
$('#empid').on('change',function() {
alert($(this).val());
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="empid" name="empname" multiple="multiple">
<option value="0">Potato</option>
<option value="1">Carrot</option>
<option value="2">Apple</option>
<option value="3">Raisins</option>
<option value="4">Peanut</option>
</select>
<br />
Hold CTRL / CMD for selecting multiple fields
If you select "Carrot" and "Raisins" in the list, the output will be "1,3".
the val
function called from the select
will return an array if its a multiple. $('select#my_multiselect').val()
will return an array of the values for the selected options - you dont need to loop through and get them yourself.
This got me the value and text of the selected options for the jQuery multiselect.js plugin:
$("#selectBox").multiSelect({
afterSelect: function(){
var selections = [];
$("#selectBox option:selected").each(function(){
var optionValue = $(this).val();
var optionText = $(this).text();
console.log("optionText",optionText);
// collect all values
selections.push(optionValue);
});
// use array "selections" here..
}
});
very usefull if you need it for your "onChange" event ;)