如何在按键时检查文本字段的新值?
我有一个表单字段,我需要能够检测该字段何时发生更改,并使用该字段的 new 值执行一些附加代码。我只想在按下的键实际上更改了文本框的值时执行代码。这是我想出的解决方案。
function onkeypress(e) {
var value = this.value;
// do something with
}
function onkeyup(e) {
if ( e.which == 8 || e.keyCode == 46 ) { // delete or backspace keys
this.onkeypress(e);
}
}
但只有一个问题。 onkeypress 在字段值更新之前触发,因此当我获取该值时,我将获取之前的值。如果我知道一种方法来测试键是否更改值,我会专门使用 keyup,但某些字符(如箭头键)对字段的值没有影响。
有什么想法吗?
I have a single form field and I need to be able to detect when the field changes and execute some additional code using the new value of the field. I only want to execute the code if the key pushed actually changes the value of the text box. Here's the solution I came up with.
function onkeypress(e) {
var value = this.value;
// do something with
}
function onkeyup(e) {
if ( e.which == 8 || e.keyCode == 46 ) { // delete or backspace keys
this.onkeypress(e);
}
}
There's just one problem though. onkeypress is fired before the field's value is updated, so when I grab the value, I'm getting the previous value. I would use keyup exclusively if I knew a way to test whether the key changed the value or not, but some characters (like the arrow keys) have no effect on the field's value.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这很简单,只需使用 onkeyup 而不是 onkeypress
this is easy, just use onkeyup instead of onkeypress
我执行此操作的方法只是使用一个类似于
prevValue
的变量。在按键函数结束时,将值存储在该变量中,并且仅当该值不等于先前的值时才再次执行该函数。The way I do this is simply with a variable along the lines of
prevValue
. At the end of the key press function, store the value in that variable, and only execute the function again if the value doesn't equal that previous value.还有另一个条件:
这将捕获特殊字符范围之外键盘输入的任何低级 ascii 符号。
编辑:(32是空格)
have another conditional:
This would catch any low level ascii symbol entered by the keyboard outside of the special char range.
EDIT: (32 is space)
这是我的最终解决方案,它使用 prevValue 变量,但不会污染全局命名空间(窗口)或 dom 元素的属性。
请注意,上面的 onkeyup 函数充当 prevValue 变量周围的闭包。这可以防止命名空间污染,因此我不必创建全局变量或将属性附加到输入元素本身。这是我所能得到的最优雅的。我实际上是用 jQuery 编写的,但认为答案本身应该是纯 JavaScript...
Here's my final solution, which uses a prevValue variable but doesn't pollute the global namespace (window) or the dom element's properties.
Notice above that the onkeyup function serves as a closure around the prevValue variable. This prevents the namespace pollution so I don't have to create a global variable or attach a property to the input element itself. This is as elegant as I can get it. I actually wrote mine in jQuery but thought the answer itself should be pure JavaScript...
这是一种黑客攻击,但您可以将以前的值放入文本框的属性中(称为“expando 属性”)
It's kind of a hack, but you can put the previous value in a property of the textbox (called "expando attributes")
您可以存储旧值并检测它是否发生变化:
You could store the old value and detect if it changed: