Problem
I'm not understanding why the input
addEventListener
change
only execute when I physically check the radio input
.
The event
should fire every time the radio
button is checked.
But it refuses to acknowledge if javascript
checkes
it (whether by click
or onkeydown
)
How would I get javascript
to fire addEventListener
change
regardless of how it was checked?
Demo
To console log:
- Press 1 or 2
(javascript does not acknowledge radio being checked)
- Click the sentence
(javascript does not acknowledge radio being checked)
- Click the radio button
let input1 = document.getElementById("input1")
let input2 = document.getElementById("input2")
let div = document.getElementById("div")
//Listens for keypress and checkes one of the radios
document.onkeydown = function (e) {
if (e.key==="1") {input1.checked = true;}
if (e.key==="2") {input2.checked = true;}
}
//Listens for sentence click and checkes one of the radios
div.addEventListener ("click", function () {
if (input1.checked){input2.checked = true;}
else {input1.checked = true;}
})
//When ever inputs are checked
input1.addEventListener ("change", function () {
console.log("Radio1 was checked")
})
input2.addEventListener ("change", function () {
console.log("Radio2 was checked")
})
#div {
padding: 10px;
background: #f5f5f5;
border-radius: 5px;
margin: 10px 0;
user-select: none;
}
<div id="div">
Click radio, click this sentence or (Press 1 or 2) to log
</div>
<input type="radio" name="a" id="input1"/>
<input type="radio" name="a" id="input2"/>