I know this has been asked a few times but I haven't seen any posts regarding the use of the labels. The code below works for deselecting a radio button when no labels are written.
How can I add labels which allow the radio buttons to be selected/deselected with the clicking of the words rather than just the radio button itself. When I add labels my code seems to go haywire.
This is the working snippet with spans instead of labels
document.getElementsByName('foo').forEach((radioBttn) => {
radioBttn.addEventListener('click', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
document.getElementsByName('bar').forEach((radioBttn) => {
radioBttn.addEventListener('click', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
<span class="foo">
<input type="radio" name="foo"> Foo</span>
<span class="bar">
<input type="radio" name="bar"> Bar</span>
<br>
<span class="foo">
<input type="radio" name="foo"> Foo</span>
<span class="bar">
<input type="radio" name="bar"> Bar</span>
<br>
<span class="foo">
<input type="radio" name="foo"> Foo</span>
<span class="bar">
<input type="radio" name="bar"> Bar</span>
This is the non-working snippet with labels instead of spans
document.getElementsByName('foo').forEach((radioBttn) => {
radioBttn.addEventListener('mousedown', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
document.getElementsByName('bar').forEach((radioBttn) => {
radioBttn.addEventListener('mousedown', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
<label class="foo" for="foo1">
<input type="radio" name="foo" id="foo1">Foo</label>
<label class="bar" for="bar1">
<input type="radio" name="bar" id="bar1">Bar</label>
<br>
<label class="foo" for="foo2">
<input type="radio" name="foo" id="foo2">Foo</label>
<label class="bar" for="bar2">
<input type="radio" name="bar" id="bar2">Bar</label>
<br>
<label class="foo" for="foo3">
<input type="radio" name="foo" id="foo3">Foo</label>
<label class="bar" for="bar3">
<input type="radio" name="bar" id="bar3">Bar</label>