009 009 - 2 months ago 6
ASP.NET (C#) Question

Get selected text from drop-down list asp.net

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")...);
}

Answer

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.

Comments