Skip to content Skip to sidebar Skip to footer

Get .val() On Keydown *not* Keyup

I'm writing a library that amends a widget to a text area, so I need to detect when the user starts typing something: this.$input.bind('keydown keyup', function() { if (this.$i

Solution 1:

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

Solution 2:

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.

Solution 3:

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

Solution 4:

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) {
    varval = 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 == …) { … }
}

Post a Comment for "Get .val() On Keydown *not* Keyup"