Learn how to implement accessible multiple selections with check boxes.
The <select>
HTML element represents a control that provides a menu of options. When used with an attribute multiple
then it allows selecting multiple options at once. However, the current implementation for multiple selections is not optimal on a desktop device so we need to find a different way. The goal would be to build multiple selections that are accessible to everyone.
Note that <select>
HTML element used with an attribute multiple
on the mobile works quite conveniently, at least what’s implemented in Chrome and Firefox browsers. You can test it on the following example code.
Multi select dropdown with checkbox goals
Let’s set the goals while building accessible multi select dropdown with checkbox in HTML5:
- Must be navigable using the keyboard.
- Must work with a screen reader.
- Easy to apply styles.
- No JavaScript code, but without handling ESCAPE key. Just pure HTML and CSS only.
- With a little JavaScript code to handle ESCAPE key.
Example code
In our example we’ll use the following major HTML elements to cover open and close behavior with multiple selections:
<details>
disclosure element<ul>
<input>
The example, initial code would start from:
<details> <summary>Your favourite cars list</summary> <form> <fieldset> <legend> Cars </legend> <ul> <li> <label for="bmw">BMW</label> <input type="checkbox" id="bmw" name="bmw" value="bmw" /> </li> <li> <label for="citroen">Citroen</label> <input type="checkbox" id="citroen" name="citroen" value="citroen" /> </li> <li> <label for="skoda">Skoda</label> <input type="checkbox" id="skoda" name="skoda" value="skoda" /> </li> <li> <label for="volvo">Volvo</label> <input type="checkbox" id="volvo" name="volvo" value="volvo" /> </li> </ul> </fieldset> </form> </details>
See workable example without JavaScript and with JavaScript to handle ESCAPE key.
Allow user to select only one checkbox
So, how can you allow the user to select only one checkbox? One way to do that is to create the change
event listener on all checkboxes, reset them all on the event handler, and set the property checked
to value true
at the end for the currently selected <input>
element. See workable example for allowing select only one checkbox without any external libraries.
Final notes
- While the example works well on the desktop device, then on the mobile may not be fully desirable. Mobile devices require a different approach adapted to the small viewport. Perhaps the best combination would be the above example on desktop and tablet and native
<select>
HTML element with an attributemultiple
to get the best user experience while still keep element fully accessible. However, it may add extra effort to implement it and the code will grow in size. - You may want to style
<form>
HTML element to be positioned absolutely to the<details>
HTML element.