使用jquery监视表单字段更改 [英] Using jquery to monitor form field changes
问题描述
尝试学习一些jquery来实现自动保存功能并需要一些帮助。我有一些代码来监视表单字段的状态,以查看是否有任何更改。一切正常,但我只需要监控特定表单中的更改,而不是页面上的所有表单输入。在同一页面上有一个搜索框和一个简报表单,当这些表单字段发生变化时,它们也会被检测到,我需要以某种方式或更好的方式过滤掉,只针对特定的表单。
Trying to learn some jquery to implement an autosave feature and need some assistance. I have some code to monitor the status of form fields to see if there has been any change. Everything works, but I need to only monitor the changes in a specific form, not all form inputs on the page. There is a search box and a newsletter form on the same page and when these form fields are changed, they are detected as well, which I need to filter out somehow or better yet, only target the specific form.
$(function(){
setInterval("CheckDirty()",10000);
$(':input').each(function() {
$(this).data('formValues', $(this).val());
});
});
function CheckDirty()
{
var isDirty = false;
$(':input').each(function () {
if($(this).data('formValues') != $(this).val()) {
isDirty = true;
}
});
if(isDirty == true){
alert("isDirty=" + isDirty);
}
}
推荐答案
在表单中添加一个类并使用它来过滤
Just add a class to the form and use it to filter
$('.form :input').each(function() {
$(this).data('formValues', $(this).val());
});
编辑
只是一个建议,您可以将更改事件直接附加到表单
Just a suggestion, you can attach the change event directly to the form
现场演示: http://jsfiddle.net/jomanlk/kNx8p/1/
<form>
<p><input type='text'></p>
<p><input type='text'></p>
<p><input type='checkbox'></p>
</form>
<p><input type='text'></p>
<div id='log'></div>
$('form :input').change(function(){
$('#log').prepend('<p>Form changed</p>')
});
您可以通过添加计时器并使其每隔xx秒保存一次来轻松改善这一点。
You can easily improve this by adding a timer and making it save every xx seconds.
这篇关于使用jquery监视表单字段更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!