Search code examples
javascripthtmljqueryaccessibility

html native dropdown - open menu items on enter click


on select enter click, by default form gets submitted on.As per accessibility criteria, if focus is on select element on enter click it should open list items. I want to know is it possible to make accessible dropdown using native select element which will meet accessibility criteria

<div class="custom-dropdown">
    <select id="cities" name="select">
       <option value="1">Delhi</option>
       <option value="2">Mumbai</option>
</select>``
</div>

I have prevented default submission behaviour.

$('.custom-dropdown').keydown(function (event) {
      if (event.keyCode == 13) {
        event.preventDefault();
        return false;
      }
});

I have tried keyup event to trigger click event but its not working

$('#cities').keyup(function (e) {
      if (e.keyCode == 13) {
        $("#cities").trigger("click");
      }
    });

Solution

  • You're basing your concern on an example, not the specification:

    The example listbox on this page implements the following keyboard interface

    If you refer to Keyboard Interaction for the Listbox Design Pattern, the Enter key is not mentioned.

    The example uses Enter, because the trigger for the listbox is a Button.

    Also, in general, ARIA rules are meant for cases where you cannot use standard elements, according to the First rule of ARIA use

    If you can use a native HTML element [HTML51] or attribute with the semantics and behavior you require already built in, instead of re-purposing an element and adding an ARIA role, state or property to make it accessible, then do so.

    In other words, you shouldn't care about those rules, when you don't implement your own controls.