Ho to toggle checkbox by pressing space while focused on label having tabindex?

Viewed 470

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 Answers

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">

Related