I'm widely using labels associated with checkbox inputs in my html. It allows user to click on the wide label and get what he wants - checkbox toggle. I want to achieve similar behaviour by pressing Space to toggle the checkbox while being focused on the label. To make label focusable I add tabindex="0"
to labels. I also don't want checkboxes to be focusable so I add tabindex="-1"
to inputs.
Here are two examples, one is using label tag wrapping, another is using for
attribute.
<input type="button" value="Click then press tab." /><br/>
<label tabindex="0">Accept terms <input type="checkbox" tabindex="-1"/></label><br/>
<label for="MyCheckbox" tabindex="0">Accept terms</label> <input type="checkbox" id="MyCheckbox" tabindex="-1"/>
I'm interested in a possibility of achieving desired behaviour without any javascript.
If the intent of the user is to bring some more space between check box "box" and its corresponding text, you can use "&npsp;" in the Text content of the checkbox. Hope that helps.
The label (Ref) element is very much focusable. Its DOM Interface is HTMLLabelElement which derives from HTMLElement (Ref) which in turn implements GlobalEventHandlers (Ref) and hence exposes the focus() method and onfocus event handler.
I think you should not set tabindex to label at all. Instead, set tabindex only to checkbox and place it outside the label. Works for me on Safari.
<input type="button" value="Click then press tab"><br>
<label for="myCheckbox">This is label</label>
<input type="checkbox" id="myCheckbox" tabindex="0">
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