Reputation: 75
How can I get selected text from drop-down list? Before crucifying me for asking a duplicate, I have read: Get selected text from a drop-down list (select box) using jQuery and Get selected text from a drop-down list (select box) using jQuery and tried the following code variations from these pages:
<asp:DropDownList ID="DDLSuburb" runat="server">
</asp:DropDownList>
alert($get("[id*='DDLsuburb'] :selected"));
alert($("[id*='DDLsuburb'] :selected"));
alert($get("#DDLsuburb option:selected"));
alert($get("DDLsuburb option:selected"));
alert($get("#DDLsuburb :selected").text());
alert($get("DDLsuburb :selected").text());
alert($get("DDLSuburb", Text));
alert($get(DDLSuburb, Text).toString());
alert($get("DDLSuburb", Text).toString());
alert($get("DDLSuburb").html());
alert($get("DDLSuburb :selected").html());
alert($get("DDLSuburb option:selected").html());
alert($get(DDLSuburb).textContent());
alert($get(DDLSuburb).innerHTML());
alert($get(DDLSuburb).innerHTML.toString());
alert($get("DDLSuburb").text());
alert($get("DDLSuburb").valueOf("DDLSuburb"));
alert($get("DDLSuburb").valueOf());
Notes: 1. I am using alert for troubleshooting. 2. I know the first part should be ($get("DDLSuburb")
, as opposed to the options without quotes. Visual Studio 2015, ASP.net.
Edit: Trying to raise the alert via button click:
<input type="button" value="Get Postcode" onclick="onClick()" />
<script type="text/javascript">
var onClick = function () {
alert($get("DDLSuburb")...);
}
Upvotes: 1
Views: 4932
Reputation: 31
this code use for show selected item by using jQuery. ddlItem is a id of dropdownlist.
<script>
$(document).ready(function () {
$("#ddlItem").change(function () {
var ddlItem = document.getElementById("<%= ddlItem.ClientID %>");
var selectedText1= ddlItem.options[ddlItem.selectedIndex].innerHTML;
alert("You selected :" + selectedText1);
});
});
</script>
Upvotes: 2
Reputation: 35514
Try
<script type="text/javascript">
$(document).ready(function () {
$("#<%=DDLSuburb.ClientID %>").change(function (e) {
alert($("#<%=DDLSuburb.ClientID %> option:selected").text());
});
});
</script>
The reason <%=DDLSuburb.ClientID %>
is used is because in the HTML the ID DDLSuburb
is translated into something like ctl00$mainContentPane$DDLSuburb
to ensure unique ID's on the page. That's why your JavaScript cannot find it.
Or you can use the property ClientIDMode="Static"
in the DropDown to keep the ID name the same in the HTML, but I do not recommend this.
Upvotes: 5