Maksym Sadovnychyy
Maksym Sadovnychyy

Reputation: 175

ASP .Net jQuery DropDownList change event

I would like to trig jQuery change event with ASP .Net. Here is the part of ASP and jQuery code:

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="body">
<p>
    <asp:DropDownList ID="DropDownList1" runat="server">
    </asp:DropDownList>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</p>
<script type ="text/javascript">
    $('#DropDownList1').change(function() {
        alert( "Handler for .change() called." );
    });
</script>
</asp:Content>

Tried to get element by id #body_DropDownList1 and #DropDownList1. Unfortunately with no output in both cases.

Upvotes: 2

Views: 24853

Answers (1)

maembe
maembe

Reputation: 1300

If you inspect the dropdownlist element in developer tools, you'll notice that the ID isn't actually DropdownList1. Asp generates an id based on the ID property to prevent duplicates, so it renders differently. You can't rely on copying the one it generates because it could potentially render it with a different ClientID. You can just set a CssClass to select though:

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="body">
<p>
    <asp:DropDownList CssClass="DropdownList1" ID="DropDownList1" runat="server">
    </asp:DropDownList>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
 </p>
 <script type="text/javascript">
    $('.DropdownList1').change(function() {
        alert( "Handler for .change() called." );
    });
 </script>
 </asp:Content>

You can also select the element based on the ClientID (the ID that is actually rendered on the client) like so:

$("#<%=DropdownList1.ClientID %>")

Upvotes: 6

Related Questions