JQuery Workaround for IE Selects
While trying to append an option to a html select and make it the selected value for a project I was working on, I noticed that although the code worked perfectly in FIrefox, the same code would add a blank entry to my select in IE. After doing some poking around I found this in a bug report on the JQuery website. Since the person reporting the bug posted a workaround, they marked it as will not fix.
Code that works in FF:
$("select[name='MySelect']").append(new Option('value', 'text', selected));
$("select[name='MySelect']").append("<option selected='selected' value='value'> command_value</option>");
$("select[name='MySelect']").append("<option selected='selected' value='" + valueVariable + "'>" + displayVariable + "</option>");
I'm a 28 year old ColdFusion, Flex, and Air programmer from Princess Anne, MD and the co-manager of the Eastern Shore of Maryland User Group (


I'm guessing append() is a jQuery-specific function, since the DOM method is appendNode() (which also works afaik).
sel = $("select[name='MySelect']"); // this seems pretty convoluted to start with, but I'll let it slide
sel.options[sel.length] = new Option('value','text',selected);
Should produce the same result... and is the standard JS syntax I believe dating all the way back to the introduction of JS or forms (I don't know which came first).
This should also work:
sel.appendNode(new Option('value','text',selected));
and so should this (courtesy w3schools who say this is part of DOM for select elements):
sel.add(new Option('value','text',selected));
I'm not saying the workaround you posted is "bad", I'm just sayin' there are several ways to do it and I don't think that's the simplest one that will work with IE. I've used the options[x] syntax and the appendNode() syntax both with IE without any problems. Haven't tried add(), that one was new for me.
I actually wasn't familiar with putting the selected value in the new option create statement either... Found this article where someone posted a script that shows 4 arguments, with the 3rd being "defaultSelected" and the 4th being "selected" and says it works all the way back to IE 5 (god I hope nobody's still using that)...
http://www.irt.org/script/1694.htm
Seems like it might be easier to just created it and set the selected property after the fact. :P
Anyway, there's my 2c.
but if you had ever TESTED out his code, you would find that
his comments are useless... His code does not work in IE. Period