1

I'm using pure javascript. There's a checkbox with a function attached to it when "onchange" event occurs.

I want to call that function, when I check and uncheck it from the javascript code.

It gets checked and unchecked but that function is not called unless I do it from manually by keyboard arrow keys.

Is there any way to make that function get called ?

HTML DOM :

<input type="checkbox" onchange="hello();" id="myCheckBox">

Javascript:

document.getElementById("myCheckBox").checked = true;
Arian
  • 7,397
  • 21
  • 89
  • 177
  • Can you post your code please ? – DavidDomain Jun 09 '16 at 08:47
  • Sorry, I just edited the question and added it. – Arian Jun 09 '16 at 08:47
  • 2
    This event does not fire when the checkbox state gets changed via script. If you want your event handler to run in such cases, then you need to trigger the event yourself from that part of the script that changes the checkbox status. http://api.jquery.com/trigger/ – CBroe Jun 09 '16 at 08:48

3 Answers3

0

The 'onchange' event is for use in text boxes and selection lists, try the 'onclick' event.

To fire an event from code you might find this useful:

How to trigger event in JavaScript?

Community
  • 1
  • 1
SPlatten
  • 5,334
  • 11
  • 57
  • 128
  • This doesn't work for me; it still doesn't trigger when I prorgammatically change the checkbox state – Ky - May 14 '21 at 03:31
0

Invoke the handler function when your JavaScript code changes the state of the checkbox elements.

function toggle() {
  document.getElementById("myCheckBox").checked = !document.getElementById("myCheckBox").checked;
  hello(); //invoke the function here!
}

function hello() {
  alert(document.getElementById("myCheckBox").checked)
}
<input type="checkbox" onchange="hello();" id="myCheckBox">

<button onclick='toggle()'>Toggle</button>
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

Use this:

HTMLInputElement.prototype.check = function() {
  if (this.checked !== null) {
    this.checked = true;
    this.onchange();
  }
};

HTMLInputElement.prototype.uncheck = function() {
  if (this.checked !== null) {
    this.checked = false;
    this.onchange();
  }
};

document.getElementById("myCheckBox").check();