View Full Version : Detect keystroke during live search

01-09-2011, 03:10 PM
Hello !

I have an ajax "live" search (using a simple input field) that returns a table with a list of players, in a div, as you type (onkeyup).

But I would like to call another javascript function (after the results are displayed, basically when readystate = 4) but only if the user press "Enter" on his keyboard.

Now how would I catch that keystroke and where would I call this function in my ajax process ?

Any help would be much appreciated!
Thanks in advance!

01-09-2011, 11:08 PM
Something like this, maybe?

var key = e ? e.which : window.event.keyCode;
if(key == 13) {
//enter pressed

01-10-2011, 10:28 AM
Hi Nile, thanks for the reply.

Yes something like that. But my main issue is where do I implement that in my existing code? Also I would like the event to occur only if I press enter while the focus is on the search input field, not on the whole window.

The problem is that the ajax search function is called each time a key is pressed in the search input field. So I would need to do the search only if another key is pressed but if "enter" is pressed, then I would call another function to display the first row details.

Actually my dream would be to be able to retrieve that table through an ajax search, then if for example the search returns 5 rows, I would be able to navigate through each row using the keyboard (up and down arrows) and select the record I want to display the details for by pressing "enter".

I have no idea if this is feasible. If someone could point me to the right direction, that would be great!

A quick example of what I want to achieve would be something like that:

- Input field onkeyup calls javascript function ->
- Check which key was pressed ->
- If standard character is entered -> ajax search
- If key 38 (up arrow) -> navigate up in table and highlight the row
- If key 40 (down arrow) -> navigate down in table and highlight the row
- If key 13 (enter key) -> call 2nd function to display details


01-10-2011, 04:53 PM
I first thought I would be able to do that by myself (with CF contribution), without using too much code but I think this is harder than expected.

Finally I found a table navigation script here:
(involves jquery and quite a lot of code, but it does what I want)

I am calling this script after the readystate==4 but added a little timeout to the tableNavigation functions so I am able to enter a few letters in my search field before the focus is set to the table to allow keyboard navigation.

-> setTimeout('jQuery.tableNavigation()', 1000);

Thread closed!

Best regards,