In this post i will tell you how can you get the selected value of the DropDownList of asp.net 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 :)
Happy programming :)
5 comments:
That's shorter:
var value = dropDownList.value;
var text = dropDownList[dropDownList.selectedIndex].text
Regards
equivoc
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.
Why asp.net? This code is applicable to any HTML SELECT element.
Andrey: yes it can be used in HTML element as well, but i have use this code with asp.net so i have mention it as asp.net.
Nice post it’s helpful to me :)
Thanks
Ashok Parmar
Post a Comment