开发者

Capturing key event for backspace

开发者 https://www.devze.com 2022-12-28 21:54 出处:网络
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

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 se开发者_StackOverflow中文版nds 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?


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消