:::: www.foddex.net ::::
      Home      |      Blog      Tutorials      Reviews      |      Resume      Portfolio      |      Photos      Stuff      |      Unreal      Flame      |      Links
Foddex' head
Contact me

Stuff
NL Weather
NL Precipitation
Temperature
xkcd
ICHC
Slashdot
Kitten
wliia
TBBT - Zoom Zoom!!

BLOG: JavaScript: selecting an option in 1 line of code

posted Mon 03-08-2009 14:15:06, in the nerd stuff (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 ]

0 comment(s)

Leave a comment

Name (required)
URL
Copy this code0-331-225-932

Pressure building on my soul
I ask God to take control
Guide me through this fucked up world

-

I know someday you'll have a beautiful life, I know you'll be a star
In somebody else's sky, but why, why, why
Can't it be, can't it be mine