Call a Javascript function on dropdownlist change

1.4k Views Asked by At

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..

2

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

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