14

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.

1 Answer 1

1

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.

Gif presenting Safari behaviour

<input type="button" value="Click then press tab"><br>
<label for="myCheckbox">This is label</label>
<input type="checkbox" id="myCheckbox" tabindex="0">

1
  • 1
    There are some cases where it would be useful to be able to completely hide the checkbox input itself (with display: none;) leaving only the label visible. In that case we would have to be able to focus on the label (with tabindex="0") and mark the checkbox by pressing space, however I don't think the last part is possible without JS :/
    – kamov
    May 27, 2022 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.