How to select multiple value from a listbox
11,737
Solution 1
Here is an example on how to do it -
HTML -
<select id="attributeNames" name="attributeNames" size="5" multiple="multiple">
<option value="Apple"> Apple </option>
<option value="Mango"> Mango </option>
<option value="Orange"> Orange </option>
<option value="Banana"> Banana </option>
</select>
JS -
window.onload = function () {
var listbox = document.getElementById('attributeNames');
listbox.onchange = function () {
for(var index = 0; index < this.children.length; index++) {
if (this.children[index].selected) {
console.log(this.children[index].value);
}
}
};
};
Solution 2
If you dont mind using jquery, -
function getUniqueValues(){
var k=0;
var selected_list = {};
$('#attributeNames option').is(':selected').each(function(){
selected_list[k++] = $(this).val();
});
alert(selected_list);
}
OR
function getrUniqueValues(){
$('#attributeNames option').is(':selected').each(function(){
alert($(this).val());
});
}
Author by
madhu
Updated on June 04, 2022Comments
-
madhu almost 2 years
I have a below code where if I select one value, it works fine, but now I need such that when I select multiple values from the listbox, i have to get the value of selected values. How do i go about it? Here is the code,
HTML Code:
<select id="attributeNames" name="attributeNames" size="5" multiple="multiple" onchange="getUniqueValues(value)"> <option value="Apple"> Apple </option> <option value="Mango"> Mango </option> <option value="Orange"> Orange </option> <option value="Banana"> Banana </option> </select>
JavaScript:
function getUniqueValues(value){ alert(value); }
For instance: If I select Apple, then I get alert saying apple, now if I select apple & mango, I have to get the alert having apple & mango values. Facing problem here.
Here is the code: http://jsfiddle.net/5VtE3/2/
Thanks in advance,