javascript select element
I have a select element like this
<select name ="cars"开发者_如何学运维>
<option value="frd"> Ford </option>
<option value="hdn"> Holden </option>
<option value="nsn"> Nissan </option>
</select>
I want to set selected to "Holden" with javascript without selected by value. how can I achieve this?
Thanks in advance
update after comment
Use the following to find the option by text and select it
var optionlist = document.getElementById('cars').options;
for (var option = 0; option < optionlist.length; option++ )
{
if (optionlist[option].text == 'Holden')
{
optionlist[option].selected = true;
break;
}
}
demo at http://jsfiddle.net/gaby/vQhfq/
original
When there is no value attribute specified for option elements, they assume the value to be the text.
I would suggest you use an id, so you can easily find the element.
Html
<select name ="cars" id="cars">
<option> Ford </option>
<option> Holden </option>
<option> Nissan </option>
</select>
javascript
document.getElementById('cars').value = 'Holden';
(make sure you run this code, after the select element is created)
demo at http://jsfiddle.net/gaby/Pwb5u/
To select the option by its text, get a reference to the select, iterate over the options looking for the one with text "Holden", then either set the select's selectedIndex property to the index of the option, or set the option's selected property to true. e.g.
function setSelectedByText(id, text) {
var select = document.getElementById(id);
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i++) {
opt = options[i];
if (opt.text == text) {
opt.selected = true;
// or
select.selectedIndex = i;
}
}
}
For the record, the value of the select element is the value of the selected option, or, if the selected option has no value, it's text. However, IE gets it wrong and returns "" if the option has no value.
Also, if you don't want to use getElementById, you can use:
var select = document.formName.selectName;
Noting that the select element must have a name to be successful (i.e. for its value to be returned when the form it's in is submitted).
精彩评论