3

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

abpetkov
  • 884
  • 5
  • 11
  • 29
  • What are you calling your "custom checkbox"? Your fiddle just has an ``, a ` – ethorn10 Apr 12 '14 at 21:23

2 Answers2

4

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:

Aditya
  • 4,453
  • 3
  • 28
  • 39
  • I don't think you get the point. I don't want to fire change events when I set the checkbox state. I know how to do that already. I need a method that detects that the checkbox is changed and does whatever it does after that. ;) – abpetkov Apr 12 '14 at 17:04
  • Ok, but you clearly mentioned in your question `Basically, I want change event to be fired` :D – Aditya Apr 12 '14 at 17:08
  • 1
    Yeah, that's why I edited as soon as I saw it's kind of confusing :) – abpetkov Apr 12 '14 at 17:10
2

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?

Community
  • 1
  • 1
phylax
  • 2,034
  • 14
  • 13
  • The thing is 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... – abpetkov Apr 12 '14 at 16:52