Issue
Okay, so I'm practicing my JS and HTML, my current code looks like this:
document.querySelector('input[name="answer"]:checked').checked = false;
let Select = document.querySelector('input[name="answer"]');
Select.addEventListener('change', function(event) {
alert(event.target.value)
})
<div>
<label><input type="radio" name="answer" value="1" checked="checked">1</label>
<label><input type="radio" name="answer" value="2">2</label>
</div>
My aim is to cancel first radio's "checked", then add an event that will show each of radio's value whenever I choose/"checked" it, but as you may notice, so far the alert will only shows up if I choose the first radio. So if I may ask, where did I do wrong and how can I fix it?
p.s. For the sake of practicing, the HTML has to stay the same. No adding Id or other selector.
Solution
- You only get the first with querySelector
- The querySelector(...:checked) will work because you can only have one checked radio
- I really like to delegate - it is recommended and makes a lot of sense
document.querySelector('input[name="answer"]:checked').checked = false;
let radDiv = document.getElementById('radioDiv');
radDiv.addEventListener('change', function(event) {
const tgt = event.target;
if (tgt.matches("[type=radio][name=answer]")) { // check we have the right elements
alert(tgt.value)
}
})
<div id="radioDiv">
<label><input type="radio" name="answer" value="1" checked="checked">1</label>
<label><input type="radio" name="answer" value="2">2</label>
</div>
Answered By - mplungjan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.