0

I'm using Visual Studio 2013 WebForms, and I'm trying to call a javascript function when a dropdownlist (Asp:DropDownList) is changed. However I am totally confused with this behavior. Could someone please tell me what is wrong?

This works

 <asp:DropDownList ID="ddlList" CssClass="form-control" onchange="alert(1)"  runat="server"></asp:DropDownList>

But nothing happens with this

$(document).ready(function () {
    function test() {
        alert(1);
    }
});

    <asp:DropDownList ID="ddlList" CssClass="form-control" onchange="test()"  runat="server"></asp:DropDownList>

and this does not work either

$(document).ready(function () {
    $('#ddlList').change(function(){
        alert(1);
    });
});

<asp:DropDownList ID="ddlList" CssClass="form-control" runat="server"></asp:DropDownList>

The hide() function works fine so I believe jquery itself works.

$("#divTextbox").hide();

This must be a simple thing but I've stack with this..

5
  • Is there any console error when the onchange doesn't work? Are you sure you tagged the script properly? Commented Jun 11, 2015 at 22:19
  • I'm debugging with FIrebug but I don't get any error messages.. Commented Jun 11, 2015 at 22:21
  • 1
    Try to change the JS to run on the CSS instead of on the ID- $('.form-control').change... does it work? Commented Jun 11, 2015 at 22:22
  • Ah yes, it works with the class name. What does that mean?? Should I use a class name or is there a way to make it work with the ID name? Commented Jun 11, 2015 at 22:24
  • 1
    Then Halcyon's solution is correct (: I highly suggest you change the ClientIDMode, this way you dont have to go the whole way around each time you try to address an element. If you need details on how to do that, just ask for it and i'll answer. Commented Jun 11, 2015 at 22:25

2 Answers 2

2

You need to modify your selector

$("#<%=ddlList.ClientID%>").change(function() {
    // do stuff here...
});

The jQuery selector you have targets the id of the server control, but when the server sends the response back, the id gets turned into some garbage like ct100_ddlList. You can also set the ClientIDMode to state on the server control.

Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly!! Thank you! I'll accept your answer in 5 minutes (SO doesn't allow me to click the accept button yet)
0

You can use ClientIDMode="Static" for ddlList if you want to use exact the same name in javascript.

Comments

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.