A coder's home for Marc "Foddex" Oude Kotte, who used to be located in Enschede, The Netherlands, but now in Stockholm, Sweden!

JavaScript: selecting an option in 1 line of code

Originally posted at 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;

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

0 comment(s)

URL: (optional!)
Write your comment:
Answer this question to prove you're human:
What year do we live in?