[英]Javascript - get value from textbox at every keypress
I have a textbox and I want to use the data in it every time something is entered; 我有一个文本框,我想在每次输入内容时使用其中的数据; letter by letter. 逐个字母。
What is happening is that when a value is entered, the Javascript is being executed before the value is actually put into the textbox, meaning that it always lags one character behind. 发生的事情是,当输入一个值时,Javascript正在执行之前 ,实际将值放入文本框中,这意味着它总是落后于一个字符。
$(document).ready(
function() {
$('#test').keypress(
function() {
var value = document.getElementById('test').value;
alert(value);
});
})
<input id="test" type="text" />
Here's whats happening: 这是最新发生的事情:
input alert
w ""
e "w"
a "we"
l "wea"
t "weal"
h "wealt"
Whereas I want it to happen dynamically; 而我希望它动态发生; ie when I enter "w" I want the alert to contain "w" immediately after. 即,当我输入“w”时,我希望警报立即包含“w”。
keypress
happens before the change, yes. keypress
发生在改变之前,是的。 keyup
happens after. keyup
发生在。 Listen to that instead. 请听一下。
你应该尝试keyup
事件,因为keypress
在文本框中输入符号之前发生
use keyup 使用keyup
$(document).ready(
function() {
$('#test').keyup(
function() {
var value = document.getElementById('test').value;
alert(value);
});
})
Use keyup
instead, take a look at this: 使用keyup
代替,看看这个:
use keyup instead that will work 使用keyup代替它将起作用
$(document).ready(
function() {
$('#test').keyup(
function() {
var value = document.getElementById('test').value;
alert(value);
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.