You might be working with ASP.NET Dropdown list or normal html dropdownlist while
working with web development. In common scenarios and day to day applications we
need to get value filed ( usually ID ) and text filed of the selected item in the
drop down.
In this post we will examine how to get selected text or selected value from the
dropdown using jQuery
Get Selected Value or Text from the Dropdownlist using jQuery
jQuery provides val() method which returns value of any element.
$("#ddlPath").val()
– gets selected value from combo or dropdownlist
$("#ddlPath").text()
– will give all the text values in side the dropdownlist.
$("#ddlPath option:selected").text() – gets the selected text from combo
or dropdownlist
for ASP.NET Dropdownlist here is the code.
$('#<%= ddlPath.ClientID %>').val()
– gets selected value for the ddlPath
$('#<%= ddlPath.ClientID %>').text() -
gets text of all options $('#<%= ddlLanguage.ClientID %> option:selected').text()-
gets selected text for the ddlPath .'
Append Values to the DropDown
The following is code to add a value to dropdown.
$("<option value=’34’>User Value</option>").appendTo("#ddlPath");
Selection change
Some times we need to do some dynamic operations based on value selected
in selection change event. That can be done as follows.
$("#ddlPath").change(function()
{
/* do something here */
});
To Set the selected value to ‘X’
$("#ddlPath").val(45);
Clear the DropDown
$("#ddlPath").empty();
To Add empty item in the first option
$("#ddlPath").prepend("");
To Select first item as default
$("#ddlPath option:first-child").attr("selected","selected");
If you are looking for certain tip using dropdownlist and jQuery, please feel free
to comment, I am ready to help you. Thanks for reading my post .