3

I have a checkbox with id myopt and I have a click event handler as 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 click the checkbox manually.

What is the issue ?

copenndthagen
  • 49,230
  • 102
  • 290
  • 442

2 Answers2

5

You need to use .trigger() to programmatically invoke the click handler

Execute all handlers and behaviors attached to the matched elements for the given event type.

Script

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

Note: I would recommend you to use change event

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

//Change
$("#myopt").prop("checked",true).trigger('change');
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

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

I have two versions depending on what you need. As I understand it, what you want is to click somewhere inside the #globalBody and check the state of myopt checkbox. In the above fiddle I did that, but I've placed in comments a code block that handles the 2nd version which is the case where you want to listen only when myopt checkbox state changes (clicks directly on the checkbox). Hope it helps

JcDenton86
  • 933
  • 1
  • 12
  • 32