Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't pressing the spacebar whilst a `label` has focus check radio button in `[for=""]` attr?

If I have the following html, when pressing the spacebar whilst the label has focus, why doesn't the radio it is associated with get checked?

<input type="radio" name="first-radio" id="first-radio-id">
<label for="first-radio-id" tabindex="1">The first radio</label>

This is making accessibility more difficult, is there a non-javascript workaround for this?

Here is a JSFiddle example: https://jsfiddle.net/atwright147/q0t53v78/

like image 820
atwright147 Avatar asked Feb 22 '16 13:02

atwright147


2 Answers

Here's a workaround that keeps tabindex for accesibility and allows to check inputs buttons with spacebar

HTML

<form>
    <label id="radio1" tabindex="0">
        <input type="radio"><span class="label-text"></span></input>
    </label>
    <label id="radio2" tabindex="0">
        <input type="radio"><span class="label-text"></span></input>
    </label>
    <label id="radio3" tabindex="0">
        <input type="radio"><span class="label-text"></span></input>
    </label>
</form>

JS

document.addEventListener('keypress', (event) => {
    if(event.keyCode == '32'){
        if (document.activeElement.tagName.toLowerCase() == "label"){
            document.activeElement.childNodes[1].checked = true;
        }
    }
});

The only downside is that the user needs to press two times tab key to go from an input to another.

BTW users with disability who have softwares like NV Access or Jaws use special keyboard shortcuts for web forms, because they know that using tab and space keys usually doesn't work.

like image 143
jck Avatar answered Nov 15 '22 18:11

jck


Label elements are not intended to receive the keyboard focus.

So simply remove the tabindex attribute and you will be able to check the radio control with the space bar when this control is focused.

If you want to control the visual aspect of a label associated to the input, you can change your CSS to:

input:focus + label {
  outline: 1px dotted red;
}
like image 29
Adam Avatar answered Nov 15 '22 18:11

Adam