Swaty
Swaty

Reputation: 59

using ajax to select an element through up/down key in keyboard for autocomplete

I am trying make an autocomplete search box using Ajax, PHP and jQuery.

I am able make selection on the search box results using mouse, i want to use key up and down to select the element.

Can you tell me how to modify the code to select the element using up/down key in keyboard instead of mouse?

<?php
if (isset($_POST['search'])) {
    $response = "<ul><li>No data found!</li></ul>";

    $connection = new mysqli('localhost', 'root', '', 'jqueryautocomplete');
    $q = $connection->real_escape_string($_POST['q']);

    $sql = $connection->query("SELECT name FROM names WHERE name LIKE '%$q%'");
    if ($sql->num_rows > 0) {
        $response = "<ul>";

        while ($data = $sql->fetch_array())
            $response .= "<li>" . $data['name'] . "</li>";

        $response .= "</ul>";
    }

    exit($response);
}
?>

Upvotes: 0

Views: 501

Answers (1)

Chandra Kumar
Chandra Kumar

Reputation: 4205

You can implement by like this code:

Click on "ok" text and try to press up down key.

Demo is here: https://output.jsbin.com/wopofom

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.js"></script>
  <script type='text/javascript'>
    $(document).ready(function() {
      $("ul").keydown(function(e) {
        switch (e.keyCode) {
          case 40:
            $('li:not(:last-child).selected').removeClass('selected').next().addClass('selected');
            break;
          case 38:
            $('li:not(:first-child).selected').removeClass('selected').prev().addClass('selected');
            break;
        }
      });
    });
  </script>
  <style type="text/css">
    .selected {
      color: red
    }
  </style>
</head>

<body>
  <div id="results" style="display: block;">
    <h4>Press Key Up and Down</h4>
    <ul tabindex='1'>
      <li class='selected'>ok</li>
      <li>ok</li>
      <li>ok</li>
      <li>ok</li>
      <li>ok</li>
    </ul>
  </div>
</body>

</html>

Upvotes: 1

Related Questions