tags:

views:

54

answers:

3

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.

A: 

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

Toby Hede
+1  A: 

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;
    }
}
Triptych
+2  A: 

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.

elo80ka
Thanks! This worked. As a side note... I found out by mistake that you can avoid the whole process by simply doing this: document.getElementById('my_selector').value=record_value;That seems to select the appropriate record without needing to find the index at all. IE will probably blow up on that, but it works in all the non-FUBARed browsers I've tried.
Y'know I had a weird hunch that'd work, though I didn't try it out. Good to know though.
elo80ka
dropdownEl.value = value works in IE as well.
einarq