Get ASP.NET Dropdown selected value and text using jQuery

In this post, I will show you how can you get the selected value and selected text of ASP.NET Dropdown using jQuery. Let's first declare the dropdown list and a button.

<asp:DropDownList ID="ddlLanguage" runat="server">
   <asp:ListItem Text="Select" Value="0"></asp:ListItem>
   <asp:ListItem Text="C#" Value="1"></asp:ListItem>
   <asp:ListItem Text="VB.NET" Value="2"></asp:ListItem>
   <asp:ListItem Text="Java" Value="3"></asp:ListItem>
   <asp:ListItem Text="PHP" Value="4"></asp:ListItem>
</asp:DropDownList>

<asp:Button ID="btnGetValue" runat="server" Text="Get DropDown Value" />

jQuery provides val() method which returns value of any element. We will use the same method to get the value of selected element in asp.net dropdown list.

$(document).ready(function(){
  $("#btnGetValue").click(function()
  {
    alert($('#<%= ddlLanguage.ClientID %>').val());
    return false;
  });
});

Now what if you want to fetch the text of selected element? Well, jQuery provides text() method also to get text of any element.

alert($('#<%= ddlLanguage.ClientID %>').text());

Oops!!! The alert message displays "Select C# VB.NET Java PHP". It is displaying text of all the element but not of selected element. To get text of selected element, try below jQuery code

alert($('#<%= ddlLanguage.ClientID %> option:selected').text());

Here, we are telling jQuery to give me text of selected element of DropDown list.

Simple and cool!!!!

Feel free to contact me for any help related to jQuery. I will gladly help you.



Responsive Menu
Add more content here...