Search code examples
javascripthtmljquerykeypressjquery-events

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.


Solution

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