Reputation: 2166
I have the following drop down list:
<select name="selSS1" id="select_value">
<option value="val0">sea zero</option>
<option value="val1">sea one</option>
<option value="val2">sea two</option>
<option value="val3">sea three</option>
<option value="val4">sea four</option>
</select>
I would like to dynamically select a value from that list using javascript:
I tried:
document.getElementById('select_value').selected ="val3";
But the above code does not seem to work. Any help is most appreciated.
Upvotes: 0
Views: 27249
Reputation: 1182
If you want to set the selected one by the value, try this function. By declaring a function you will be able to use this functionality with any select :).
// Simplest version
function setSelected(select_id,value){
document.getElementById(select_id).value = value;
}
// Or, complex version
function setSelected(select_id,value){
var mySelect = document.getElementById(select_id);
var options = mySelect.options;
var key;
for(key in options){
if(options[key].value===value){
options[key].setAttribute("selected","");
}
else
options[key].removeAttribute("selected");
}
}
in your case:
setSelected("select_value","val3");
Upvotes: 0
Reputation: 2471
THis will select val 3
document.getElementById('select_value').selectedIndex=3;
Upvotes: 0
Reputation: 825
Try it this way:
document.getElementById('select_value').option[3].selected;
Upvotes: 0
Reputation: 5647
With plain JavaScript:
var element = document.getElementById("select_value");
var selectedValue = element.options[element.selectedIndex].value;
Upvotes: 0
Reputation: 2123
Use the following line:
document.getElementById('select_value').value ="val3";
or
document.getElementById('select_value').selectedIndex = 3;
Hope this solves ur problem.
Upvotes: 6
Reputation: 3436
try:
var mySelect = document.getElementById('select_value');
mySelect.getElementsByTagName('option')[index].setAttribute('selected','selected');
where index stands for the position of the option you want to select.
Upvotes: 1