posted Mon 03-08-2009 14:15:06, in the nerd stuff ( ) category
Recently I stumbled upon a nice new feature in JavaScript, by accident really, one I haven't seen documented anywhere yet (not here, here, here or even here)! Fellow JavaScript coders most likely recognize the inconvenience of having to iterate through a select object's array of options if you want to select a specific option through code. It usually turns out to be code like this:
var s = document.form.mySelect;
for (var i=0; i=s.options.length; ++i)
if (s.options[i].value==valueToBeSelected)
{
s.selectedIndex = i;
break;
}
However, there's a new shiny hammer to do this, and it works in Firefox 3.5 and Internet Explorer 6 and 8 (haven't tested any other browsers): simply set the value property of the select!
document.form.mySelect.value = valueToBeSelected;
Lot less code aye!
Confirm whether or not it works in your browser by clicking the following buttons:
-- Foddex
[ Back to blog listing ]
| More nerd stuff...200920072006 |