WebDevelopersNotes logo

home-icon Home / HTML / Getting the text from an HTML drop down selection list

Getting the text from an HTML drop down selection list

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.

Sponsored Links

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>

Click here to see how it works!

Sponsored Links

Your comments
Star icon IMPORTANT Have a question / problem? Click here to ask an expert.

Sponsored Links

Tips

How do I view a deleted web page?
Is there a way to view a deleted web page - one that is no longer available? Yes there is and the solution is quite simple. [more...]

Fact

Brian Klug came across an item on Amazon.com carrying a price of $3 billion with $3.99 shipping. Out of curiosity, he ordered it from the Amazon affiliate. The order was processed but later cancelled. The reason given was "unable to complete the order". [more...]