views:

34

answers:

3

I have a <select> that depending on previous options is populated by a var with a bunch of <option> values.

Naturally, because IE doesn't work with innerHTML I have to append this template to the <select> which now works great in IE. HOWEVER I now need a way to clear out the select options from the previous search and in FF stop it from dropping down to the last <option> in the list.

+1  A: 

Just rewrite the entire select block using innerHTML, that always works.

eBusiness
A: 

Well using YUI3:

    node.setContent(template); //removes old children, sets new template as content.
    node.set('selectedIndex', 0); //forces FF to select the first one

Edited with correct methods.

+1  A: 

Foolproof way of clearing out the options from a <select>:

while( select_control.length > 0 )
     select_control.options[0] = null

Some browsers will clear the list if you do select_control.length = 0 but I've found this unreliable.

Foolproof way of inserting option:

var new_option = new Option(text, value)
try {
    select_control.add(new_option, select_control.options[0])
} catch(e) {
    select_control.add(new_option, 0)
}

The 0 is the index of the item you want your item before. To add it to the end, do this instead:

select_control.options[select_control.length] = new_option

This will also work if you want to replace a specific item, by specifying the index of an existing option.

staticsan
That's some good information, however I found that running new Option 100 times in a loop locks IE up on some computers.
Okay, I hadn't encountered that bug! I normally only want to add one or two. If I have a whole list to repopulate, I would instead normally render each list and fiddle with the CSS `display` attribute to just show the correct one. (Of course, the server side has to know to look at the correct form element, too.)
staticsan