06 Feb, 2007
Javascript set selection in select element
Posted by: Jennifer In: Javascript|jquery|Script snippet
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;
}
}
Update Posting my comment in the main post – because this is the way to do it right: Use jQuery because it rules.
Use this plugin:
http://www.texotela.co.uk/code/jquery/select/
And this code:
$(document).ready(function() {
$(”#selectboxname”).selectOptions(”The Select Value”, true);
});