In
this post, I'll show how you can get the selected text and selected value of dropdown
using jQuery. Dropdown can be ASP.Net dropdown or HTML dropdown.
Let’s
define one dropdown and button:
<!--Dropdown can be either of
ASP.Net -->
<asp:DropDownList ID="ddlGender" runat="server">
<asp:ListItem Value="1">Male</asp:ListItem>
<asp:ListItem Value="2">Female</asp:ListItem>
</asp:DropDownList>
<!--Or HTML select-->
<select id="ddlGender">
<option value="-1">-Select-</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<input type="button" id="getValue" value="Get Value"/>
|
Getting
value with jQuery is quite easy with the help of val() method, which returns
value of any selected element.
Though
fetching out selected text of dropdown is tricky though. jQuery provides text()
method which returns text of any element. But if we use text() method directly against
dropdown object then it’ll return all text of the element and not of selected
element, so to get selected text we first need to find selected item and then use
text() method.
$('#getValue').click(function (event) {
//Get the selected value and
text for Asp.Net Dropdown.
alert($('[id$=ddlGender]').val());
alert($('[id$=ddlGender]').find('option:selected').text());
//Or get the selected value and
text for HTML select.
alert($('#ddlGender').val());
alert($('#ddlGender').find('option:selected').text());
return false;
});
|
nice
ReplyDelete