Select a dropdown option by value 「JavaScript」

A very simple and common issue a Javascript newbie often faces is how to select a dropdown option dynamically by value. People who are working for long with Javascript would solve it in minutes, but Hey! this is for a newbie, remember?

So this is a simple function to do the work.

function selectItemByValue(elements, value){ for(var i=0; i < elements.options.length; i++) { if(elements.options[i].value == value) elements.selectedIndex = i; } }

Parameters elements: This is the select box taken by functions like "getElementById" or any other way. value: This is the value which needs to be selected from the options of elmnt.

Example
Lets say you have an HTML select box like below:

I have put an id in the select field to make it easy to get it by ID in a bunch of select fields. What we need to do is, first get the element object and pass it to the function along with the value you want to select. Lets say, we want to select Three. So our Javascript code should look like this:

Hope it works well for you. ^^

Credit: Imranul Hoque

K

Read more posts by this author.

Somewhere in this world http://khay.me
comments powered by Disqus