How To Get The Selected Value From Select Drop Down Using Javascript

The desired behavior is to access the selected value from the select tag (select drop down list) by creating a javascript function that can be applied with an event handler (most likely onclick).  Here is an example of the markup:

[code lang="html"]

[/code]

Now what we want to do is use Javascript to access the value of the option tag that a user selects. In this example, I have made the values URLs, so that when a user selects an option and clicks the submit button, they will be sent to the correct URL.

First, we want to access the drop down list. The drop down menu is the select tag, or the select node in the DOM. I have given my select tag an id, named “mylist”. Your select tag can have any id name you want.

Keep in mind that option nodes are children of the select node, in the form of an array. Once we have gotten the id of our select list, using getElementById, we can then get the options of the list by using the options[] property which returns an array of all the options in a dropdown list. But instead of accessing the whole array, we just want to access the specific option selected, so we can use the selectedIndex property which does just that. But what we REALLY want is the value of the selected option, so we add the value property on the end.

Also notice that I set the value of the selected option equal to window.location.href, which means it will send the value as a link to a page, which is the behavior we want when someone clicks the submit button.

[code lang="javascript"]
function goValue() {
var sel = document.getElementById("mylist");
window.location.href = sel.options[sel.selectedIndex].value;
}
[/code]

There are other ways of doing this function, but this one I have found to actually work in all browsers with no difficulties. Enjoy!

Here is a formula to follow to target the selected option. Name your form and your select menu, then you can target the selected option:
[code lang="javascript"]
document.myForm.myList.options[document.myForm.mylist.selectedIndex].value;
[/code]

[code lang="html"]

[/code]

This entry was posted in Javascript, Uncategorized and tagged , . Bookmark the permalink.

Comments are closed.