Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the NEW value of an HTML text input during a keypress event via jQuery?

I can only retrieve the value without the newly pressed key. Using the keyup event isn't an option, because it does not fire if the user doesn't release the key. This is important because I want to act upon every single keypress.

Combining the old value with the keyCode that is reachable from the event's arguments isn't acceptable either, because it's not guaranteed that the user will type to the end of the string in the textbox.

like image 242
Attila Kun Avatar asked Aug 11 '10 23:08

Attila Kun


2 Answers

Wrap your handler code in setTimeout(function() { ... }, 0).

This will execute the code in the next message loop, after the value has been updated.

like image 118
SLaks Avatar answered Nov 15 '22 07:11

SLaks


It's possible to work out what the value will be after the keypress. It's easy in non-IE browsers and trickier in IE, but the following will do it:

document.getElementById("your_input").onkeypress = function(evt) {
    var val = this.value;
    evt = evt || window.event;
    var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode;
    if (charCode) {
        var keyChar = String.fromCharCode(charCode);
        var start, end;
        if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
            start = this.selectionStart;
            end = this.selectionEnd;
        } else if (document.selection && document.selection.createRange) {
            // For IE up to version 8
            var selectionRange = document.selection.createRange();
            var textInputRange = this.createTextRange();
            var precedingRange = this.createTextRange();
            var bookmark = selectionRange.getBookmark();
            textInputRange.moveToBookmark(bookmark);
            precedingRange.setEndPoint("EndToStart", textInputRange);
            start = precedingRange.text.length;
            end = start + selectionRange.text.length;
        }
        var newValue = val.slice(0, start) + keyChar + val.slice(end);
        alert(newValue);
    }
};
like image 41
Tim Down Avatar answered Nov 15 '22 05:11

Tim Down