'HTML onchange event sometimes fires twice on input checkbox element
This happens to me in Chrome 79.0.
CodePen replicating the issue: https://codepen.io/puckowski/pen/eYmEbVz
I have a basic input
element which looks like:
<input type="checkbox">
In JavaScript, I define an onchange
property like so:
let eventObj = {
onchange: function() { console.log('event fired'); }
}
I then set my input
element's onchange
property like so:
for (let [k, v] of Object.entries(eventObj)) {
vType = typeof v;
if (vType === 'function') {
inputElem[k] = v; // inputElem is the correct element in the document and not undefined
}
}
Effectively, inputElem
is defined by:
inputElem = document.getElementById('foo');
The onchange
event is bound only once per the method above.
When I click on the checkbox, sometimes the onchange
event fires once, sometimes it fires twice.
This doesn't seem to be an event bubbling issue. If I change the bound function to the following:
function(evt) { console.log('event fired'); evt.stopPropagation(); }
The onchange
event will still fire twice occasionally.
Any ideas as to what is going on? Is this perhaps a element focus issue?
Solution 1:[1]
Here is what worked fine for me:
function(evt) {
console.log('event fired');
evt.stopImmediatePropagation();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Murillo |