Skip to content
Advertisement

JQuery search box autosuggest – How to select from suggestions with arrow keys whilst still retaining focus on input field

I have a search box that has an autosuggest feature, so it adds suggestions to an unordered list within an absolutely positioned div below the search box. These suggestions are sourced via ajax using JQuery/PHP.

This is all working fine, with one caveat. One has to click one of the suggestions with the mouse manually to follow the link.

What I would like to achieve is something similar to google suggest where the top option is automatically selected and one can move up or down using the arrow keys.

I’m not expecting someone to write this code for me, but just a plain English description of the best way to go about this. I can’t get my head around how the text input can stay in focus as well as the list item also being selected and visitable via a press of enter key.

One thought I have had is styling the background color of the “selected” item differently to the others and storing it’s target url somehow elsewhere, then listening for keypress of enter to redirect to the stored url using JS.

I would appreciate any thoughts as to the best way to do this. Thanks in advance.

Advertisement

Answer

I have done this once. I wrote a code with the following logic:

I’ve created a function to set “focus” to the list items. This function received a parameter of the key event. Inside it, it verified the key if was up or down. If yes, then it checked if the list has more itens to go down(in case of down key) or go up(in case of up key), if yes, change it. This change was made by another function. If it has not items to change, juts keep it.

If the key was enter, it just activate the action(url link, event, whatever).

The change function can just receive an index, then it clean the “selected” style of all items and add that style to the selected ones. At the start of the search, you just have to set the change function to index 0 of the list.

I’m afraid that this is the main(almost complete) proccess. Is that all what you want?

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement