1. Computing & Technology

JavaScript By Example

DOM Form: 10. Getting The Selected Option

From , former About.com Guide

Unlike radio buttons where it is possible to start with none of the buttons in a group selected, a select list always has an option selected. If you do not specify which option you want selected by default the first option will be selected.

While some browsers map the value and textfrom the selected option to the select itself, you can't rely on that non-standard behaviour in obtaining those values.

In this example we create a getOption function where we can pass the id of a select list and return an object with value and text properties that are those of the currently selected option.


getOption = function(id) {
var selbox;
selbox = document.getElementById(id);
return {
value: selbox.options[selbox.selectedIndex].value,
text: selbox.options[selbox.selectedIndex].text};
}


Reader Submissions: Help Others By Providing Your Own JavaScript Examples

JavaScript By Example
Related Searches radio buttons first option map

©2012 About.com. All rights reserved.

A part of The New York Times Company.