Thursday, December 25, 2008

How to Get Selected Value From DropDownList Using Javascript

In this post i will tell you how can you get the selected value of the DropDownList of control using javascript. It is simple code but i think this will help you. Below is the sample code you can use in your cod.

function getSelectedItem(dropDownList)
//get the selected index of the dropDownList
var intSelectedIndex = dropDownList.selectedIndex;
//check if there is selected item or not
if(intSelectedIndex != -1)
//get the value of the dropDownList
var value=dropDownList.options[intSelectedIndex].value;
//get the text of the dropDownList
var strText= dropDownList.options[intSelectedIndex].text;
what ever you like to with the value and the text as you
get these properties of the dropDownList

In the above code i have use function getSelectedItem which take dropDownList control object as parameter. In the first statement of the function i have get the selectedIndex of the dropDownList and store it in the variable intSelectedIndex . In the next line i have use the if condition to check whether selectedIndex is not equal to the -1 which indicate nothing is is selected. If selectedIndex is not equal to the -1 then it mean user have selected some value in the dropDownList, In the if condition block i have used that selectedIndex to get the value and the text of the dropDownList item. I have store the value and text in seperate variable so that you can use it whatever your need is. Hope this will help you and if you have any question please do ask me.
Happy programming :)


equivoc said...

That's shorter:

var value = dropDownList.value;
var text = dropDownList[dropDownList.selectedIndex].text


Asim said...

equivoc: Thanks for your comments and very nice suggestion too , for selecting the value directly instead of using the index, thanks a lot for your comments.

Andrey said...

Why This code is applicable to any HTML SELECT element.

Asim said...

Andrey: yes it can be used in HTML element as well, but i have use this code with so i have mention it as

Rem said...

nice blog...
visit also example

Anonymous said...

Nice post it’s helpful to me :)

Ashok Parmar