开发者

Get .val() on keydown *not* keyup

I'm writing a library that amends a widget to a text area, so I need to detect 开发者_如何学JAVAwhen the user starts typing something:

this.$input.bind('keydown keyup', function() {
    if (this.$input.val() == …) { … }
}

The .val() only updates when keyup is triggered. That's too much of a delay. I want to know the state of the input box on keydown. Do you know of a library that improves .val()?


too late? can't imagine a scenario where 10ms would make that much of a difference, but you could always examine the event args and get the char from there. or try keypress.

edit: there's also the input event that gets fired as soon as the input changes (before keyup, but after the value changes);


The only way to determine the character at keydown/keypress is by using the event.keyCode or event.which property (where event is an object, passed as a first argument to the event listener function).

Swap your events for the keypress event. This event listener is fired while the key is pressed down. keydown and keyup are only fired once. During the keydown/keyup event, multiple characters could have been added.


Found a seemingly perfect solution. Uses aforementioned HTML5 oninput with onpropertychange fallbacks for IE. Brilliant. Fantastic. Other happy words.


For a keypress (ex. the "a" key), the keydown event is triggered before the "a" is appended to the text input. You could detect the event type, and whether the .keyCode (or .which) event property was a key in the printable range, and attempt to predict what .val() might return after the keyup event, but this is a bad idea.

this.$input.bind('keydown keyup', function(e) {
    var val = this.$input.val();

    if (e.type == 'keydown') {
        // Here is where you would check to see if e.keyCode was a printable
        // character.  Note that key codes differ from ASCII codes. For
        // example, the "a" key will return key code 65, which is actually
        // the ASCII code for "A", so you would need to check for the presence
        // of shift keys and such.  Again, this is a bad idea :)
        val += String.fromCharCode(e.keyCode);
    }

    if (val == …) { … }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜