How to select an option in a select box by the value of the option using Javascript?
I have a select box that is populated with all the available options it can have. Whe开发者_JAVA技巧n a user clicks on a record in my application, I get an xml response that includes the value of the option for that record. I'd like to use javascript to set the selected index for that particular option in the select box without having to reload the select box. Is there an easy way to find the index of an option based on the value or name of the option? Then, I could set that option as the selected index.
I'd second Toby's answer. Still, if you can't use an existing library for some reason, it's easy enough to do in plain javascript:
function selectByValue(el, value) {
for (var i=0, len=options.length; i<len; i++) {
if (el.options[i].value == value) {
el.selectedIndex = i;
break;
}
}
}
If you'd like to use the text of the option instead, replace .value
with .text
. I assume you meant "text" since select options don't have a "name" property.
It'll be pretty close to this:
function find_index(options, value) {
for (var i=0; i<options.length; i++) {
if (options[i].value == value) {
return i;
}
}
return -1
}
function set_selected_option(select_element, value) {
var index = find_index(select_element.options, value)
if (index != -1){
select_element.selectedIndex = index;
}
}
I would suggest having a look at a JS library like jQuery or Prototype. They make this kind of thing easy.
精彩评论