What <select> HTML element is?
<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.
<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 keyboard.
- Must work with a screen reader.
- Easy to apply styles.
In our example we’ll use the following major HTML elements to cover open and close behavior with multiple selections:
The example, initial code would may 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>
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
changeevent listener on all checkboxes, reset them all on the event handler, and set the property
trueat the end for the currently selected
<input>element. See workable example for allowing select only one checkbox without any external libraries.
- 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 best combination would be above example on desktop and tablet and native
<select>HTML element with an attribute
multipleto get the best user experience while still keep element fully accessible. However, it may add extra efforts to implement it and the code will grow in size.
- You may want to style
<form>HTML element to be positioned absolutely to the