Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

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

Solution 2:

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 (typeofthis.selectionStart == "number" && typeofthis.selectionEnd == "number") {
            start = this.selectionStart;
            end = this.selectionEnd;
        } elseif (document.selection && document.selection.createRange) {
            // For IE up to version 8var 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);
    }
};

Solution 3:

Here's an idea that might work. Use keypress and store the val at that point so you can always compare the current value to the last value and find the difference in the strings. The difference will be the key that was pressed.

One way to do this would be to turn the strings into arrays and compare the 2 arrays like they are doing here: JavaScript array difference

Never tried anything like this so it might not be viable but might be worth a shot.

Solution 4:

I had a specific case with TAB key, which changes the e.target in keyUp, so that's solution - bind to container element, grab target input in keyDown handler, subscribe to keyUp and read the value.

$("#container").keydown(function (e) {
   //here you decide whether to handle the key event, and grab the control that sent the event var myInput = e.target;
   $("#container").one('keyup', function() {
      console.log(myInput.val());  
      // do smth here
   });
});

Post a Comment for "How Can I Get The New Value Of An Html Text Input During A Keypress Event Via Jquery?"