Liste de suggestions accessible

18 mars 2025

Introduction

L'élément HTML <datalist> contient un ensemble d'éléments <option> qui représentent les valeurs possibles pour d'autres contrôles.
Nativement accessible, plus besoin de librairie JavaScript pour faire une liste de suggestions si vous êtes prêt à faire une croix sur la personnalisation graphique.
J'ajoute un petit script pour les lecteurs d'écran afin de faciliter son usage.

Code

<label for="ice-cream-choice">Choose a flavor:</label>
<input 
       list="ice-cream-flavors" 
       id="ice-cream-choice" 
       name="ice-cream-choice" 
       autocomplete="off"
       />
<p id="suggestions-help" role="status" aria-live="polite" class="visually-hidden"></p>

<datalist id="ice-cream-flavors">
  <option value="Chocolate"></option>
  <option value="Chocolate White"></option>
  <option value="Dark Chocolate"></option>
  <option value="Coconut"></option>
  <option value="Mint"></option>
  <option value="Strawberry"></option>
  <option value="Vanilla"></option>
</datalist>
.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border-width: 0;
}
const inputField = document.getElementById("ice-cream-choice");
const datalist = document.getElementById("ice-cream-flavors");
const help = document.getElementById("suggestions-help");

function hasCommonSubstring(str1, str2) {
  return str1.includes(str2) || str2.includes(str1);
}

inputField.addEventListener("input", () => {
  let value = inputField.value;
  let options = datalist.options;
  let suggestionsCount  = 0;

  for (let i = 0; i < options.length; i++) {
    if (
      hasCommonSubstring(value.toLowerCase(), options[i].value.toLowerCase())
    ) {
      suggestionsCount++;
    }
  }
  if (suggestionsCount > 0 && suggestionsCount < options.length ) {
    help.textContent=`There are ${suggestionsCount} suggestions. Use the up and down arrows to browse.`;
  }
});

Rendu

See the Pen Dialog by Pierre TL (@pierre_tl) on CodePen.

Retour en haut