views:

23

answers:

2

I've got a "search" box that is supposed to be able to search data "live". Right now if I attach the "keypress" event to it and update the results, it works pretty good. However, if they press backspace it doesn't account for that (refresh the results).

I understand I can probably account for the "backspace" key.

But am I missing any other possibilities? I want any change of the text in the input to be triggering the "event" or calling the refresh function.

The one thing I don't want to do is set "alarms" or "timers" to check every so often if it has changed.

Ideas?

+1  A: 

To insure that you are triggering your data search after each changing of the text field, you should check if the text field has changed after each .keyup() or .keydown()

$(function() {                         // <== Doc ready  

    var inputVal = $("input").val();   // a variable to hold the text
                                       // set it up w the initial value then see 
                                       // if the input value changes.

    $("input").keyup(function() {

        // check for change of the text field after each key up
        if(this.value != inputVal)
        {
            // Do your search, etc.
            // ...

            // Reset the temp value for the next comparison
            inputVal = this.value
        }
    });
});

Try it out with this jsFiddle

Peter Ajtai
+1 for jsFiddle
Mike Webb
A: 

Take a look at Common event behaviors (which is about event behaviors that are shared by different kinds of input elements in HTML5). In particular, the change event is supposed to do what you want. (One of these decades, anyway.) It should, at least, be safe to handle this event, even if many browsers don't yet support it.

SamB
The `change` event is only triggered on blur for text fields, so it wouldn't really work in this case. From http://api.jquery.com/change/ ==> `For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.`
Peter Ajtai
@Peter: Oops, missed that...
SamB