Javascript jquery输入值变化检测
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8043440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery input value change detection
提问by Yekver
How to detect was input value changed or not on blur event?
如何检测输入值是否在模糊事件中发生变化?
For example every input field have default value (can be empty), after current input loose it's focus we should determine, have the value been changed.
例如,每个输入字段都有默认值(可以为空),在当前输入松动后,我们应该确定其焦点是否已更改。
How to do this?
这该怎么做?
采纳答案by Dr.Molle
compare the valueand the defaultValue
比较值和默认值
<input onblur="if(this.value!=this.defaultValue){alert('changed');}">
回答by Darin Dimitrov
回答by Jemaclus
You could switch to the .change() event instead of .blur(), but I believe that to be fundamentally flawed in a variety of ways. I suggest using Jonathan Azoff's Changed jQuery plugin (http://www.azoffdesign.com/changed). That may be overkill in this case, so...
您可以切换到 .change() 事件而不是 .blur(),但我认为这在很多方面都存在根本性的缺陷。我建议使用 Jonathan Azoff 的 Changed jQuery 插件 ( http://www.azoffdesign.com/changed)。在这种情况下,这可能有点矫枉过正,所以......
There are many ways to do this, one of which is to store the old value as a data attribute for an input, then compare the value of the input to the old value on blur. If the two values are different, then it changed.
有很多方法可以做到这一点,其中一种方法是将旧值存储为输入的数据属性,然后将输入值与模糊时的旧值进行比较。如果两个值不同,那么它就改变了。
Example:
例子:
<input type="text" name="firstname" data-old="Hyman">
You can store this value using your back-end type thing, or even do it on page load. Then on blur, you can have an event that works something like this:
您可以使用后端类型存储此值,甚至可以在页面加载时存储。然后在模糊时,你可以有一个像这样工作的事件:
$('input').blur(function() {
if ($(this).data('old') != $(this).val())
// It changed! Do something!
}
If the old value was "Hyman", and then you changed the name to "Bob" and triggered the blur event, it would see that "Hyman" is not equal to "Bob", and perform your action.
如果旧值是“Hyman”,然后您将名称更改为“Bob”并触发了模糊事件,它会看到“Hyman”不等于“Bob”,并执行您的操作。
Hope that helps. Good luck.
希望有帮助。祝你好运。
回答by comu
Directly from the jQuery documentation
直接来自 jQuery 文档
$("input[type='text']").change( function() {
// check input ($(this).val()) for validity here
});
回答by pomaxa
You can save value of input on focus, and check it with value from input on blur.
您可以保存焦点输入的值,并使用模糊输入的值检查它。