abpetkov
abpetkov

Reputation: 914

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

Upvotes: 3

Views: 1444

Answers (2)

Aditya
Aditya

Reputation: 4463

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:

Upvotes: 4

phylax
phylax

Reputation: 2086

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?

Upvotes: 2

Related Questions