Javascript set selection in select element
I needed to set the selection of a drop down menu. As far as I can tell, if you don’t know the “index” value, then you just have to loop through to set the item as selected. If there’s an easier way to do this, please speak up in the comments. I spent WAY too long hunting for a better solution, but this was the only thing that worked:
for (var i=0; i < document.formname.dropdownboxname.length; i++) {
if (document.formname.dropdownboxname[i].value == “value”) {
document.formname.dropdownboxname[i].selected = true;
}
}
February 6th, 2007 at 6:19 pm
If you give the options an id, then you can use that to set the selected value. A co-worker of mine figured out how to go about it, and I’ve used it myself.
For example, if you have the following:
option 1
option 2
option 3
And you want to select the option with a value of “2″, you can do:
document.getElementById(”option2″).selected = true;
If you name your options in a consistant, predictable manner, then it’s not too difficult to do.
I hope that helps (and that I made sense explaining it).
February 7th, 2007 at 4:39 pm
Oops. Looks like some of my comment got eaten.
My example should have been …
[option value="1" id="option1"]option 1[/option]
[option value="2" id="option2"]option 2[/option]
[option value="3" id="option3"]option 3[/option]
March 1st, 2007 at 8:53 am
Thanks to all. This works like a champ. I had several drop-down selects, and gave the options an id in the form of [id of select].[id of option] to keep them straight.
August 27th, 2007 at 7:38 am
Was looking for just this script. Thank you for saving me 3 hours.
March 11th, 2008 at 6:10 pm
Was looking for this script. Too bad you don’t have ads on this site — I would have clicked on all your ads as a form of thank you.
(You really should sign up with Google AdSense if you’re going to post this kind of stuff. I just started last month and with just one blog and without even trying, I managed to get $20. Imagine if I had dozens of blogs, useful info like this, and actually made an effort at it.)
June 15th, 2008 at 2:30 am
Or use jQuery:
http://docs.jquery.com/Attributes/val#val