Is there a difference between "change" and "click" when listening to checkboxes in Javascript?

2

Seeing that these two pieces of code work the same, I would like to know if there is any difference between click and change at the time of listening to the events in the elements checkbox of Javascript.

Test with click :

document.addEventListener("DOMContentLoaded", function(e) {
  var allChecksBoxes = document.querySelectorAll("input[type='checkbox']");
  allChecksBoxes.forEach(function(el) {
    el.addEventListener("click", checkOnClick);
  });
});

function checkOnClick() {
  console.log('click: ' + this.value);
}
<h2>Click</h2>
<legend>Elija opción</legend>
<hr />
<input type="checkbox" name="cbxTest" value="1" />Opción 1<br />
<input type="checkbox" name="cbxTest" value="2" />Opción 2<br />
<input type="checkbox" name="cbxTest" value="3" />Opción 3<br />

Test with change :

document.addEventListener("DOMContentLoaded", function(e) {
  var allChecksBoxes = document.querySelectorAll("input[type='checkbox']");
  allChecksBoxes.forEach(function(el) {
    el.addEventListener("change", checkOnChange);
  });
});

function checkOnChange() {
  console.log('change: ' + this.value);
}
<h2>Change</h2>
<legend>Elija opción</legend>
<hr />
<input type="checkbox" name="cbxTest" value="1" />Opción 1<br />
<input type="checkbox" name="cbxTest" value="2" />Opción 2<br />
<input type="checkbox" name="cbxTest" value="3" />Opción 3<br />
    
asked by A. Cedano 06.02.2018 в 22:56
source

1 answer

1

The only important difference I have observed is that the response time (activation) of the event change suffers a "delay" in the versions under 9 of the IE browser because to be able to Activating requires that the checkbox lose focus after being pressed.

The event click does not present the problem mentioned above and in view of this it is advisable to use it to ensure the correct functioning of the system in all browsers.

I have also noticed some flaws in the operation of the change in the checkbox using certain HTML tags such as <label> , a situation that has never happened to me with the event click . This information is explained in detail in a response given in English version. Here the link: Change and Click on checkbox

    
answered by 07.02.2018 в 01:50