Selecting an option with JavaScript

Normally you would select an option with a server-side script like PHP which is a lot faster and doesn't require the client's browser to do the work. But on the rare occasion where you need to set an option with JavaScript, here's a small script on how to do it.

 
document.getElementById('select_box_id_here').value
 = 'the value of the one you want selected';
 

This will work if you have constructed the page the proper way. On the odd chance you've used JavaScript to pull in a whole string of HTML then use the method below.

 
var selectBox = document.getElementById('select_box_id_here');
for(i=0; i
<selectBox.options.length; i++) {
	if(selectBox.options[i].value == a_value) {
		selectBox.options[i].selected = true;
		i = selectBox.options.length;
	}
}
 

The above script simply loops through your select box and determines if the current option (in the loop) matches the value (a_value), if so then set the option to selected. The line "i = selectBox.options.length;" simply stops the 'for loop' from checking any further options.

The reason why you have to manually go through the select box yourself is because the DOM doesn't actually know the select box is on the page when you've just dumped a whole lot of HTML into the page with JavaScript. If it's possible to refresh the DOM then let me know, otherwise the above option is the solution to this problem.

This entry was posted on Sunday, November 9th, 2008 at 8:45 pm and is filed under Programming, javascript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

4 Responses to “Selecting an option with JavaScript”

Dave, the post has been updated, thanks for your comment.
Hi Dave, thanks for your comment.

That method doesn't work in a particular web browser, trying to find out now but not having any luck. I think it's IE6, I'll test it on my work's Mac tomorrow. I know of a situation where the script you've supplied doesn't work, I'll come back to this post after extensive testing.
Try:

document.getElementById('select_box_id_here').value = a_value;

instead.
Try:

document.getElementById('select_box_id_here') = a_value;

instead.

Leave a Reply