Selected Text and Value of ASP.NET DropDownList using jQuery

I recently saw a question on StackOverflow where a user wanted to retrieve the selected value of an ASP.NET DropDownList using jQuery. I have observed a lot of developers confused on when to use text() vs val().

Here’s the solution taken from my EBook 51 Recipes with jQuery and ASP.NET Controls

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
<
title>Get Selected Value and Text From ASP.NET DropDownList</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript">
$(function () {
$('select[id$=DDL]').bind("change keyup", function () {
$('#para').html(
"Value: " + $(this).val() +
"<br />" +
" Text: " + $('select[id$=DDL] :selected').text());
});
});
</script>

</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
h2>Select an Item from the DropDownList to display
it's text and value </h2>
<
asp:DropDownList ID="DDL" runat="server" >
<
asp:ListItem Text="Select an Item" Value="" />
<
asp:ListItem Text="Item3" Value="3"></asp:ListItem>
<
asp:ListItem Text="Item1" Value="1"></asp:ListItem>
<
asp:ListItem Text="Item4" Value="4"></asp:ListItem>
<
asp:ListItem Text="Item5" Value="5"></asp:ListItem>
<
asp:ListItem Text="Item2" Value="2"></asp:ListItem>
</
asp:DropDownList>
<
br /><br />
<
p id="para"></p>
</
div>
</
form>
</
body>
</
html>

In this example, both the change and keyup event of the DropDownList is captured using bind(). According to the W3C specifications, the change event occurs when a control loses the input focus and its value has been modified since gaining focus. However IE triggers the ‘change’ event as soon as the option is selected, whereas Mozilla, Chrome and Safari do not. This behavior of triggering the change event by IE on keyboard scrolling is not according to the W3C specs. This is the reason that we use both the change and keyup event to capture selection, when the user uses the keyboard to scroll through the dropdownlist items.

Whenever the user selects a new item from the DropDownList, the ‘value’ is printed using $(this).val() and the ‘text’ is printed using $(‘select[id$=DDL] :selected’).text().

The :selected selector matches selected <option> elements. The results are written to a paragraph using $(‘#para’).html()

When the user selects an item from the DropDownList, the output looks similar to the one shown below:

image

See a Live Demo

This entry was posted in ASP.Net, jQuery, Syndicated. Bookmark the permalink.

Comments are closed.