You can see it here: https://jsfiddle.net/vt0u2ddk/
var items = document.getElementsByTagName('input');
for (var i = 0; i < items.length; i++) {
items[i].onclick = function(e) {
alert('clicked');
console.log('clicked', e.target.value);
};
}
<div id="text">
<input name="auto" value="foo" type="radio" checked>foo</label>
<input name="auto" value="bar" type="radio">bar</label>
<input name="auto" value="ming" type="radio">ming</label>
</div>
If you click on a radio button (not the label) first, you get an alert for a click event. If you then use the arrow keys to switch the selection of the radio list, each time a click event gets triggered. Why? I'm using my keyboard and not my mouse. Is there a explanation and/or workaround for this?
I'd suggest using the mouseup event instead. The click event considers switching radio buttons to be a left click (for some reason, verify this by checking e.button), but mouseup properly recognizes the difference between the two and will not fire when using the keyboard. My testing seems to verify that mouseup properly recognizes raising your finger from a touch event too, but I'm not 100% on that point.
var items = document.getElementsByTagName('input');
for (var i = 0; i < items.length; i++) {
items[i].onmouseup = function(e) {
alert('clicked: ' + e.button);
console.log('clicked', e.target.value);
};
}
<div id="text">
<input name="auto" value="foo" type="radio" checked>foo</label>
<input name="auto" value="bar" type="radio">bar</label>
<input name="auto" value="ming" type="radio">ming</label>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With