While working on a web application I had the need to dynamically add new Option elements to a Select element (drop down list) using some fancy client-side JavaScript. The obvious solution was to do something like this:
var theSelectList = $('theBigFatSelectList');
var myNewOption = new Option("My Option", "123");
theSelectList.selectedIndex =
InsertNewOption(myNewOption, theSelectList);
function InsertNewOption(newOption, selectElement)
{
var optsLen = selectElement.options.length;
selectElement.options[optsLen] = newOption;
return optsLen;
}
And it worked just as I’d expected. I got a new option in the drop down list and all was right with the world. At least in Firefox... but not so in IE7. WTF!?!
I attached my debugger to IE7 and was able to reproduce the error. According to the debugger selectElement.options.length had a value of something like 155, so that was good. But why the Object doesn’t support this property or method error?
I had no idea what was wrong... everything looked OK to me and it worked like a charm in Firefox. So like the good developer I am I decided to blame it on Internet Explorer!
Stinking JavaScript oddities!
This one had both Tyler and I banging our heads for a little while. I even did a little Googling and it seemed my code was exactly how everyone else in the world would do it... almost.
I noticed a variation in .ctor signatures some of code samples were using. Some used a .ctor with just two arguments, like the one in the code above, others were using four arguments. Huh?
I looked up some documentation on the various .ctors and found that the four argument version was probably a better fit for my use case, so I decided to try it.
Trying something different
After a little clean up I ended up with the following code:
var theSelectList = $('theBigFatSelectList');
AddSelectOption(theSelectList, "My Option", "123", true);
function AddSelectOption(selectObj, text, value, isSelected)
{
if (selectObj != null && selectObj.options != null)
{
selectObj.options[selectObj.options.length] =
new Option(text, value, false, isSelected);
}
}
Success!
I’m not still not sure if it’s the .ctor or that the new code doesn’t use a local variable to hold the length of array... but it works!
Yeah, I know I should do a deeper dive into this and figure out exactly what it was that was causing the problem, but sometimes time just doesn’t permit such endeavors. As my dad likes to say
It’s good enough for who its for.