How to open jQuery-UI-Selectmenu dropdown using 'ENTER' key using custom logic? Documentation only allows 'SPACE' key to open but not 'Enter' key

261 views Asked by At

I am trying to use jQuery-UI-Selectmenu for a dropdown functionality.

According to the API documentation provided for select menu at https://api.jqueryui.com/selectmenu/, 'SPACE' key can be used to open select menu but not 'ENTER'.

A basic HTML select can be opened using 'ENTER' key but not the select menu. For accessibility requirement, I need to get the select menu opened using 'ENTER' key as well.

Could you please help. Below is the code I am using to create the dropdown.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Nuber</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css"> 
  <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
  <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
  <script>
  $( function() { 
    $( "#number" )
      .selectmenu()
      .selectmenu( "menuWidget" )
        .addClass( "overflow" );
  } );
  </script>
</head>
<body>
 
<div class="demo"> 
<form action="#"> 
    <select name="number" id="number">
      <option>1</option>
      <option >2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
</form> 
</div> 
</body>
</html>
1

There are 1 answers

0
Patrick Hume On

It's a bit hacky but you could do something like this (may have to click enter twice the very first time) :

<!doctype html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Nuber</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
    <script>
      $(function() {
        let isOpen = false
        $(".container").on("keydown", function(event) {
          if (event.which === 13) {
            isOpen = !isOpen
            if (!isOpen) {
              $("#number").selectmenu("open");

            } else {
              $("#number").selectmenu("close");

            }
          }
        })



        $("#number").selectmenu()
          .selectmenu("menuWidget")
          .addClass("overflow");
      });

    </script>
  </head>

  <body>
    <div class="container">
      <form action="#">
        <div id="foo">
          <select name="number" id="number">
            <option>1</option>
            <option>2</option>
            <option>3</option>
            <option>4</option>
            <option>5</option>
            <option>6</option>
          </select>
        </div>
      </form>
    </div>
  </body>

</html>

I hope this helps