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,
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);
}
}
};
};
Live Demo.
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());
});
}
You might want to try checkboxes
<input type="checkbox" name="fruit" value="apple">Apple<br/>
<input type="checkbox" name="fruit" value="banana">Banana
Or you should just try to make:
<select id="attributeNames" name="attributeNames" size="5" multiple="multiple" onChange="getUniqueValues()" >
<option value="Apple"> Apple </option>
<option value="Mango"> Mango </option>
<option value="Orange"> Orange </option>
</select>
function getUniqueValues(){
var values = this;
}
Try this:
<select id="attributeNames" onchange="getUniqueValues.call(this)" 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>
function getUniqueValues(){
for(var i = 0; i < this.options.length; i++){
if(this.options[i].selected)
alert(this.options[i].value);
}
}
jsfiddle: http://jsfiddle.net/5VtE3/7/