3
votes

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

2
What are you calling your "custom checkbox"? Your fiddle just has an <input type="checkbox" class="chbx" />, a <button> and a <div>...no sign of any hidden inputs. Can you update your fiddle to more accurately reflect your updated question? - ethorn10

2 Answers

4
votes

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:

2
votes

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?