Activating label to check a checkbox by pressing enter

Hey, clicking a label linked to a checkbox checks and unchecks the checkbox however if the label is tabbed on and you press enter it doesn't activate. When you do this on an a tag for example it works perfectly okay, how do i make this function work on a label? Many thanks.
4 Replies
Chris Bolson
Chris Bolson8mo ago
You need to set the focus and other events on the checkbox, not on the label. However checkboxes are "checked " by pressing the spacebar, not the "enter" key. If you want to change this behaviour you are probably going to have to use JS.
snxxwyy
snxxwyyOP8mo ago
ah i understand, i apprecitate the help
Chris Bolson
Chris Bolson8mo ago
Something like this should work.
document.querySelectorAll('label').forEach(label => {
label.addEventListener('keypress', () => {
if (event.key === 'Enter') {
const checkboxId = label.getAttribute('for');
const checkbox = document.getElementById(checkboxId);
checkbox.checked = !checkbox.checked;
}
});
});
document.querySelectorAll('label').forEach(label => {
label.addEventListener('keypress', () => {
if (event.key === 'Enter') {
const checkboxId = label.getAttribute('for');
const checkbox = document.getElementById(checkboxId);
checkbox.checked = !checkbox.checked;
}
});
});
snxxwyy
snxxwyyOP8mo ago
oh awesome, thank you for taking the time to write that.
Want results from more Discord servers?
Add your server