Chekbox click event not firing on checkout

I have a checkbox with the id myopt and I have a click event handler as shown below:

$("#globalBody").on("click", "#myopt", function (event) {
    if ($(this).prop("checked")) {
        // do something
    } else {
        // do something
    }
});

      

Now in my code I do

$("#myopt").attr("checked",true);

      

My question is this does not trigger the click event handler above. It gets called if I manually check the checkbox.

What is the problem?

+3


source to share


2 answers


You need to use .trigger()

to programmatically invoke the click handler

Execution of all handlers and behaviors associated with the appropriate elements for this event type.

Script



$("#myopt").prop("checked",true).trigger('click');

      

Note. I would recommend that you use the eventchange

$("#globalBody").on("change", "#myopt", function (event) {
    if (this.checked) {
        // do something
    } else {
        // do something
    }
});

//Change
$("#myopt").prop("checked",true).trigger('change');

      

+5


source


Check this fiddle please https://jsfiddle.net/kwp7sjwf/2/



I have two versions depending on what you need. As I understand it, you want to click somewhere inside #globalBody

and check the box myopt

. In the above script, I did it, but I posted in the comments a block of code that handles the second version where you only want to listen when the checkbox state changes myopt

(clicks directly on the checkbox). Hope it helps.

0


source







All Articles