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;
}
}

5 Responses to “Javascript set selection in select element”

  1. Becky Says:

    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).

  2. Becky Says:

    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]

  3. Rick Says:

    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.

  4. Will Says:

    Was looking for just this script. Thank you for saving me 3 hours.

  5. volomike Says:

    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.)

Leave a Reply