Jquery methods (click,change) not working

1255 views javascript
2

I am in process to upgrade the code of cakephp 2.6 application to cakephp 3.7 the jquery code written in the view files under the application not working anymore which was working earlier.

Below is the code sample which is not working

$(document).ready(function () { 
    $("#CouponAllowTime").click(function () {           
        if ($(this).is(":checked")) {
            $("#timeDiv").show();
        } else {
            $("#timeDiv").hide();
        }
    }
}

But when I tried to run code using $(document).on(), it works

$(document).ready(function () {    
    $(document).on('click','#CouponAllowTime',function () {            
        if ($(this).is(":checked")) {
            $("#timeDiv").show();
        } else {
            $("#timeDiv").hide();
        }
    }
}

I don't want to change several files of the application for this change, what is an issue here?

answered question

when any dynamic html you write after page load, then you need to use $(document).on() instead of $("#CouponAllowTime").click()

I know, but I am not writing any html after page load. HTML element for "#CouponAllowTime" id is load initially with the page. Same code is working on live site I am doing change in my local host

1 Answer

11

The issue could be while upgrading from one version to another version, controls are generated dynamically. To attach event on dynamically created element you have to use delegation approach using .on().

posted this

Have an answer?

JD

Please login first before posting an answer.