Reputation: 1647
hi I need to get all the values selected in a drop down box.Please see the example.
<html>
<head>
<script>
function getSelected()
{
alert(document.myform.mytextarea.value);
return false;
}
</script>
<title></title>
</head>
<body>
<form name=myform>
<select id=mytextarea size=3 multiple>
<option id=one value=one> one </option>
<option id=two value=two> two </option>
<option id=three value=three> three </option>
<option id=four value=four> four </option>
</select>
<input type="button" onclick="getSelected();"/>
</form>
</body>
</html>
How to retrieve all the multiple values selected in the dropdown.Rightnow I am getting only one value
Upvotes: 2
Views: 1552
Reputation: 166336
Try this function
function getSelected()
{
var lst = document.myform.mytextarea;
for (var i = 0; i < lst.options.length; i++)
if (lst.options[ i ].selected)
alert(lst.options[ i ].value);
return false;
}
Found here
How to get selected items from using Javascript
Upvotes: 2
Reputation: 187020
You can use something like this
function getSelected()
{
var dropDownElem = document.getElementById ( "mytextarea" );
var selectedValues = new Array();
var dropDownLength = dropDownElem.length;
for ( var i=0; i < dropDownLength; i++ )
{
if ( dropDownElem.options[i].selected )
{
selectedValues.push ( dropDownElem.options[i].value );
}
}
alert ( selectedValues.toString() ); // gets the values separated by ','
alert ( selectedValues.join(';') ); // gets the values separated by ';'
}
Note
Also a good practice to move your javascript from HTML side. Remove you onclick handler from HTML and bind that inside your <script>
tag.
Upvotes: 4
Reputation: 21500
You can try something like:
var select = document.getElementById('mytextarea');
var selected = new Array();
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].checked) {
selected.push(select.options[i]);
}
}
Upvotes: 0
Reputation: 162771
Try this:
function getSelected() {
var selections = new Array();
var options = document.getElementById('mytextarea').options;
for (var i=0; i<options.length; i++) {
if (options[i].selected) {
selections[selections.length] = options[i].value;
}
}
return selections;
}
Upvotes: 0
Reputation: 19598
Try this
function getSelected()
{
for(var i=0; i <= document.myform.mytextarea.options.length - 1; i++)
{
if(document.myform.mytextarea.options[i].selected)
{
alert(document.myform.mytextarea.options[i].value);
}
}
return false;
}
Upvotes: 0
Reputation: 9959
http://www.digitalamit.com/blog/blog/23.html
var selected = new Array();
for (var i = 0; i < mytextarea.options.length; i++)
if (mytextarea.options[ i ].selected)
selected.push(mytextarea.options[ i ].value);
Upvotes: 0