Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 586
Ivan Gritsenko Avatar asked Mar 11 '16 16:03

Ivan Gritsenko


People also ask

How do you put a space between text and checkbox in HTML?

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.

Is label focusable element?

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.


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">
like image 92
Pyry Lahtinen Avatar answered Oct 16 '22 10:10

Pyry Lahtinen