使用jQuery监测表单字段的更改

13

我试图学习一些jQuery来实现自动保存功能,需要一些帮助。我有一些代码来监视表单字段的状态,以查看是否有任何更改。一切正常,但我只需要监视特定表单中的更改,而不是页面上所有表单输入。在同一页上有一个搜索框和一个新闻通讯表单,当这些表单字段发生变化时,也会触发监测,我需要找出一种方法来过滤它们,或者更好的方式就是只针对特定的表单。

$(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);
    }
}
8个回答

28

只需给表单添加一个类,并使用该类来进行筛选

$('.form :input').each(function() {
    $(this).data('formValues', $(this).val());
});

编辑

只是一个建议,你可以直接将change事件附加到表单上。

这里有一个演示: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秒保存一次来轻松改进此功能。


虽然在Firefox(以及可能其他浏览器)中可以直接将更改事件附加到表单,但如果您使用jQuery 1.3.2或更低版本,则在IE8中无法正常工作...我认为这取决于.live()与.change()的配合。http://jsfiddle.net/kNx8p/17/ - scunliffe

2
var $jq= jQuery.noConflict();
         $jq(function() {                       $jq('#extensibleForm').data('serialize',$jq('#extensibleForm').serialize());
 });


function formHasChanged(){
      if($jq('#extensibleForm').serialize()!=$jq('#extensibleForm').data('serialize')){
              alert("Data Changed....");
              return (false);
}
return true;
}

1

你的表单id是什么?

你只需要使你的选择器更加具体 :)

使用:

$('#yourFormId').find(':input').each(function() {

1
你可以使用 .change() 函数,然后使用 $(this) 来表示你只想处理当前正在被更改的字段。
$('#myForm input[type="text"]').change(function() {

    $(this)...

});

编辑:#myForm 是您的表单 ID,因此您可以针对特定表单进行定位。您甚至可以在该表单中仅指定 type="text" 字段,就像我的示例一样。


$('#myForm input:text') 选择相同的元素,而且更加简洁... :text-选择器 - David Thomas

1

在这里你可以看到它的工作效果:http://jsfiddle.net/paska/zNE2C/

$(function(){
    setInterval(function() {
        $("#myForm").checkDirty();
    },10000);
    $("#myForm :input").each(function() {
        $(this).data('formValues', $(this).val());
    });

    $.fn.checkDirty = function() {
        var isDirty = false;

        $(this).find(':input').each(function () {
            if($(this).data('formValues') != $(this).val()) {
                isDirty = true;
            }
        });

        if(isDirty == true){
            alert("isDirty=" + isDirty);
        }
    };
});

0

我尊重所有有效的答案,但我认为使用 focus 事件比使用 change 事件更好。以下是我在 JavaScript 中实现 watchChange() 函数的方式:

 var changeInterval = 0;
 var changeLength = 0; //the length of the serverData
 var serverData = {value:''}; //holds the data from the server
 var fieldLength = 0; //the length of the value of the field we are tracking
 var frequency = 10000;

  function watchChange() {
    $input.on('focus', function() {
    var $thisInput = $(this);

    //we need the interval value so that we destroy
    //setInterval when the input loses focus.
    changeInterval = setInterval(function() {

        changeLength = serverData.value.length;
        fieldLength = $thisInput.val().length;

        //we only save changes if there is any modification
        if (changeLength !== fieldLength) {
            $.ajax({
                url: 'path/to/data/handler',
                dataType: 'json',
                data: "data=" + $thisInput.val(),
                method: 'post'
            }).done(function(data) {
                serverData = data;
            }); //end done
        } //end if

    }, frequency); //end setInterval

    //and here we destroy our watcher on the input
    //when it loses focus
}).on('blur', function() {
    clearInterval(changeInterval);
});

}

尽管这种方法看起来很幼稚,但它给了我想要的!

0
您可以为表单元素指定一个id属性(例如theForm),然后仅选择其中的输入字段。
然后尝试使用以下方式进行选择:
$(':input', '#theForm')

0
我认为你可以使用一个类来选择你想要的输入类型。
<input class="savethis" ... />

然后在 jQuery 中使用这个。

$(':input .savethis').each(function() { ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接