Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - jQuery keyboard events

Using jQuery, I would like to capture a keyboard event that is:

  • before the user lifts their finger from the key
  • after the characters from the keyboard event have registered in the input box.

To clarify, view this example. When keypress fires, the input value has not been updated yet.

[Edit]

Apparently I wasn't clear as to what I need.

The function must be called before the user lifts their finger up from the key, but after the key's character is placed in the input box. So the following do not work:

  • keydown: at the keypress event, the value in the text box has not been updated
  • keypress: at the keypress event, the value in the text box has not been updated
  • keyup: this is called when the user lifts their finger, which is too late.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the input event, which works in recent versions of all major browsers:

var input = document.getElementById("your_input_id");
input.oninput = function() {
    alert(input.value);
};

Unfortunately, it doesn't work in IE <= 8. However, in those browsers you can use the propertychange event on the value property instead:

input.onpropertychange = function() {
    if (window.event.propertyName == "value") {
        alert(input.value);
    }
};

SO regular JavaScript answerer @Andy E has covered this in detail on his blog: https://web.archive.org/web/20140626060232/http://whattheheadsaid.com/2011/10/update-html5-oninput-event-plugin-for-jquery


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...