user77413
user77413

Reputation: 31235

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. When 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.

Upvotes: 0

Views: 402

Answers (3)

elo80ka
elo80ka

Reputation: 15845

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.

Upvotes: 3

Kenan Banks
Kenan Banks

Reputation: 212058

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;
    }
}

Upvotes: 1

Toby Hede
Toby Hede

Reputation: 37133

I would suggest having a look at a JS library like jQuery or Prototype. They make this kind of thing easy.

Upvotes: 0

Related Questions