2

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.

1
  • Can you put the HTML generated on browser for the drop down list? Commented Mar 20, 2015 at 18:15

1 Answer 1

6

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 %>")
Sign up to request clarification or add additional context in comments.

1 Comment

<script type ="javascript"> - was wrong, should be <script type ="text/javascript">, your example is working in this way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.