开发者

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.


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

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


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


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.


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜