Tags: defaultSelected, ie, ie6, ie6 bug, options, select, selected, selectedIndex
While working on getting ChainedSelects to work on IE6, I realized there are multiple ways to set an option as selected. Since ChainedSelects creates all the options for a pre-existing select, I first used the defaultSelected argument passed in the Option constructor:
option = new Option("name", "value", true);
Here, the third argument specifies whether the option is defaultSelected, when the select is first created or the form is reset. This worked fine in Firefox but IE6 blythely ignored it. So I tried passing a fourth argument that specifies whether the option is currently selected.
option = new Option("name", "value", true, true);
Again, Firefox does the right thing but IE6 gets wacky and incosistently selects the correct option or sometimes does nothing at all. It seems as if IE6 misses the “selected” message on the event queue, because it works only when i put some alert()s in there.
So I tried another way, by using the selected attribute after creating the option:
option = new Option("name", "value", true, true); option.selected = true
Again, inconsistent behavior on IE6. I went to the great oracle and asked google and tried setting the selected attribute to ‘selected’, ‘true’, and ‘yes’ all with no luck. I wonder if this occurs because the select is pre-existing and is not newly created. This led me to try out the selectedIndex attribute on the select element.
select = $('myselect') select.selectedIndex = 3
Bingo! This works in both Firefox and IE. The index is 0-based as you would guess (0 is the first option is select.options).