jump to navigation

selectedIndex is your friend on IE6 November 5, 2008

Posted by reidmix in Code, Example, Javascript.
Tags: , , , , , , ,
trackback

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

Advertisements

Comments»

1. Erwin Draft - December 22, 2008

Thx alot for your post here, help me a lot!

2. reidmix - December 22, 2008

Yer welcome ;D

3. Alexwebmaster - March 3, 2009

Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: