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
182 views
in Technique[技术] by (71.8m points)

javascript - Detecting "value" of input text field after a keydown event in the text field?

My site has an input box, which has a onkeydown event that merely alerts the value of the input box.

Unfortunately the value of the input does not include the changes due to the key being pressed.

For example for this input box:

<input onkeydown="alert(this.value)" type="text" value="cow" />

The default value is "cow". When you press the key s in the input, you get an alert("cow") instead of an alert("cows"). How can I make it alert("cows") without using onkeyup? I don't want to use onkeyup because it feels less responsive.

One partial solution is to detect the key pressed and then append it to the input's value, but this doesn't work in all cases such as if you have the text in the input highlighted and then you press a key.

Anyone have a complete solution to this problem?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The event handler only sees the content before the change is applied, because the mousedown and input events give you a chance to block the event before it gets to the field.

You can work around this limitation by giving the browser a chance to update the field's contents before grabbing its value - the simplest way is to use a small timeout before checking the value.

A minimal example is:

<input id="e"
    onkeydown="window.setTimeout( function(){ alert(e.value) }, 1)"
    type="text" value="cow" />

This sets a 1ms timeout that should happen after the keypress and keydown handlers have let the control change its value. If your monitor is refreshing at 60fps then you've got 16ms of wiggle room before it lags 2 frames.


A more complete example (which doesn't rely on named access on the Window object would look like:

var e = document.getElementById('e');
var out = document.getElementById('out');

e.addEventListener('input', function(event) {
  window.setTimeout(function() {
    out.value = event.target.value;
  }, 1);
});
<input type="text" id="e" value="cow">
<input type="text" id="out" readonly>

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

...