How to get text from a selection list or an HTML drop down list using JavaScript code.

Custom Search

Sponsored Links

Getting the text from an HTML drop down selection list

The drop down selection list is an element of HTML forms. It consists of a set of options along with their associated values and some text. This text (not the value) is displayed in the drop down selection list.

<FORM NAME="myform">
<SELECT NAME="mylist">
<OPTION VALUE="m1">Cape Fear
<OPTION VALUE="m2">The Good, the Bad and the Ugly
<OPTION VALUE="m3">The Omen
<OPTION VALUE="m4">The Godfather
<OPTION VALUE="m5">Forrest Gump
</SELECT>
</FORM>

The list is displayed like:

It's quite easy to obtain the value of a selection list option through the value property.
Thus,

document.myform.mylist.value

will return the value of the item chosen from the list, which will be m1, m2, m3, m4 or m5.

To get the text from each option is slightly trickier. We use the selectedIndex property of the selection list to capture the selected option and then pass this value to the options[].text property.
Here is the code

var w = document.myform.mylist.selectedIndex;
var selected_text = document.myform.mylist.options[w].text;

This code can be placed in a function that can be called using an event handler, say onChange(), inside the selection list.

// The following code should be stored in the HTML head section
function disp_text()
   {
   var w = document.myform.mylist.selectedIndex;
   var selected_text = document.myform.mylist.options[w].text;
   alert(selected_text);
   }


<FORM NAME="myform">
<SELECT NAME="mylist" onChange="disp_text()">
<OPTION VALUE="m1">Cape Fear
<OPTION VALUE="m2">The Good, the Bad and the Ugly
<OPTION VALUE="m3">The Omen
<OPTION VALUE="m4">The Godfather
<OPTION VALUE="m5">Forrest Gump
</SELECT>
</FORM>

Select an option from the drop down menu above.


Page contents: Details on how to extract the text of an item from an HTML drop down selection list using clever JavaScript coding.

AddThis Social Bookmark Button

HTML & JavaScript Tips