How can I get a new HTML text input value during a keypress event through jQuery?

I can only get the value without a recently pressed key. Using the keyup event is not an option because it does not fire if the user does not release the key. This is important because I want to work on every keystroke.

Combining the old value with the key code accessible from the event arguments is also unacceptable, since it does not guarantee that the user will print to the end of the line in the text box.

+5
source share
4 answers

, . , IE, IE, :

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

setTimeout(function() { ... }, 0).

value.

+6

, . keypress val , . .

- 2 , : JavaScript

, , .

+1

I had a specific case with a TAB key that changes e.target to keyUp, so the solution is that it binds to the container element, captures the target input in the keyDown handler, subscribes to keyUp and reads 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
source

All Articles