1

I have autocomplete code which shows a popup containing matches after a user has entered 3 characters or more in a text field. Standard stuff.

The pop up is simply a div, within which there is a list containing matches, e.g.

<div id="popup">
  <ul>
    <li><a href="/link1">Link 1</a></li>
    <li><a href="/link2">Link 2</a></li>
  </ul>
</div>

Question is, how can I make it so that when a user presses the tab key from within the text input field, it jumps to the first in the list of <li> elements?

Is this possible?

I tried setting tabindex on the <li> elements but this had no effect.

I'm using vanilla javascript, NOT JQuery

StudioTime
  • 22,603
  • 38
  • 120
  • 207
  • Take a look at http://stackoverflow.com/questions/18316395/javascript-for-handling-tab-key-press#answer-18316711, you can then adapt this (http://stackoverflow.com/questions/4583476/scrolling-to-li-element-jquery#answer-24361061) to jump to / focus / whatever – ggdx Oct 09 '14 at 12:44

2 Answers2

-1

You could use stylized form elements to accomplish that without having to script.

-2

I think you could look for key press events in the input form and if user press tab then set focus on the first result and prevent default behaviour. Further tabbing would work as normal.

Something like this:

function maybeTab(e) {
  if (e.keyCode == 9) {
    // it was tab
    document.querySelector("#popup ul li:first-child a").focus();
    return false;
  } else {
    // it wasnt tab
    return true;
  }
}
#popup {
  border: 1px solid #00a;
}
a:active, a:focus {
  background-color: #ff0;
}
<input type="text" name="search" id="search" onkeypress="return maybeTab(event);">
<a href="/linkB">Link InBetween</a>
<div id="popup">
  <ul>
    <li><a href="/link1">Link 1</a></li>
    <li><a href="/link2">Link 2</a></li>
  </ul>
</div>
Jonas Äppelgran
  • 2,617
  • 26
  • 30