Selecting A Radio Button Or Checkbox By Clicking The Words Around It
Radio buttons and checkboxes within a HTML form are generally quite small, especially when completing a form using a mobile phone. As a result, to improve accessibility, you may have seen other websites make it possible to also tick the inputs by clicking or tapping on the word immediately nexyt to it.
To demonstrate what I mean let’s take a look at the checkbox below:
Have a go at clicking the words to the right of the checkbox and you’ll notice that the input is ticked and unticked accordingly. Now let’s take a look at the code that is behind the above:
<input type="checkbox" name="myCheckbox" id="myCheckbox" value="1"> <label for="myCheckbox">This is a checkbox. Click here to tick it.</label>
There are two main things to getting this to work:
1) Add a <label> tag around the words that we want to link to the input.
2) Set the ‘for’ attribute of the label to match the ID of the input. In the example above, both the checkbox and the label were linked using the ‘myCheckbox’ ID.
So there we have it. It’s also worth noting that this isn’t only applicable to radio buttons and checkboxes, but can infact be applied to all types of input, including text fields and textareas.