Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox not firing onchange event when triggered

Here's a preview of my problem - JSFiddle.

Basically, I want change event to be fired, when I change the input state programatically like this:

el.checked = true;

But the event is fired only when I directly click on the checkbox, which doesn't work for me.

EDIT: Some clarification: I'm already dispatching a change event when the button is clicked and it's working just fine. What the problem is, is that I have custom checkbox element and the native input is hidden. So when I click the custom checkbox - the change event is fired properly. But when I change the native checkbox state, the custom checkbox is not changing, because I have no way to detect that change...

What I need is some custom method that detects this checkbox change and tells me "here, your checkbox is changed".

like image 247
abpetkov Avatar asked Dec 10 '25 05:12

abpetkov


2 Answers

I got it to work using dispatchEvent:

button.addEventListener('click', function() {
    if (input.checked) input.checked = false;
    else input.checked = true;

    if ("createEvent" in document) {
      var evt = document.createEvent("HTMLEvents");
      evt.initEvent("change", false, true);
      input.dispatchEvent(evt);
    }
    else
    input.fireEvent("onchange");
});

Here is the Working Fiddle:

like image 114
Aditya Avatar answered Dec 11 '25 20:12

Aditya


Event handler in JavaScript dont react on programmatical changes. You have to call the handler from your code.

However when you have no access to the event handler you could try creating your own event and dispatch it on the input. Here is a related post: Is it possible to dispatchEvent() a mouse click to a <input type=text> element?

like image 24
phylax Avatar answered Dec 11 '25 21:12

phylax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!