Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing key event for backspace

I am having difficulty capturing the backspace key as a keyboard Event in javascript/jQuery. In Firefox, Safari, Opera, Chrome, and on the iPhone/iPad, I capture a keyup event on a text input box like this:

$(id_input).keyup(function(event) {
   that.GetHints($(this).val().trim(), event, fieldName);
});

This event captures user keystrokes, then sends them to a function to issue an ajax lookup call.

My problem comes when a user wishes to backspace over a character he/she already typed. In all the browsers to which I have access except for my Droid phone, when I press the backspace key, this keyup event captures the value returned by $(this).val().trim() and sends it on to process in function GetHints. On the Droid, however, neither this keyup nor an equivalent keydown event fires until the user backspaces over every character in $(this).

So, for example, if I type "cu" then backspace over the "u" leaving only "c" in the input field, in all browsers except Droid, the keyup event will fire and call function GetHints("c", event, fieldName). On the Droid, the keyup event never fires.

What am I missing? How/why does this backspace key, on either the soft keyboard or the hard keyboard, on my Droid not function as expected? How do I work around this?

like image 857
Jeff Falter Avatar asked Apr 27 '10 18:04

Jeff Falter


1 Answers

You could poll for changes in the text (using setInterval). This would probably be more reliable. For example, keyup wouldn't fire if the user does right-click -> cut. Polling alone would be less responsive, but you could combine it with keyup to keep it snappy. Polling would be a bit more processor heavy.

Try something along these lines:

var oldText = '';
var timer = setInterval(function(){
    var text = $(id_input).val().trim();
    if(text != oldText){
        oldText = text;
        that.GetHints(text, fieldName);
    }
}, 500);

Tweak the interval duration as necessary.

I'm not sure what that.GetHints does with event, but obviously, you wouldn't be able to pass that in using the polling approach (because there isn't an actual event being fired). Is this a problem?

You can use clearInterval(timer); to stop polling if you want to.

You could keep your existing keyup function as it is (to increase responsiveness). Alternatively, you may wish to just poll to avoid that.GetHints being called too much (e.g. if someone types something in really quickly).

like image 144
Spycho Avatar answered Oct 27 '22 06:10

Spycho