找出HTML表单是否发生了变化 [英] Find out if html form has changed

查看:116
本文介绍了找出HTML表单是否发生了变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jquery我已经添加了一个表单处理器。
只有当用户手动更改输入,而不是某些其他代码更改输入时,此功能才适用于任何输入。



有没有办法检测一个表单是否已经改变,即使它的输入被代码改变了?

解决方案

是的,似乎对此有些困惑。在一个理想的世界里,你会期望每当输入发生变化时都会发生onchange事件,但那不会发生什么。我肯定有很好的理由 - 也许不是。

我克服这个障碍的一种方法是在显示它之后将窗体状态捕获到变量中,然后就在提交它之前检查状态是否已经改变并采取相应的行动。

一个简单的状态来存储是序列化函数返回的内容。存储状态的一个简单的地方是使用数据功能。 序列化数据是可用的jQuery。



当然,您可以使用其他不同形式的状态(某种形式的哈希)或存储此状态(例如标准全局变量)。



以下是一些原型代码:

如果您的表单ID是'xform',那么您可以调用以下代码当表单显示时:

  $('#xform')。data('serialize',$('#xform' )。连载()); 

然后,当您需要检查时,例如在按钮提交之前,您可以使用:

  if($('#xform')。serialize()!= $('#xform')。data('serialize ')){
//表单已更改!
}

你可以将所有这些都包含在一个副本&粘贴JavaScript片段,它会给你一个 formHasChanged()函数来调用你需要的任何地方(未测试):

<$数据('序列化',$('#xform')。serialize()); $ b $($#$)$('#xform')。 b});
函数formHasChanged(){
if($('#xform')。serialize()!= $('#xform')。data('serialize')){
return真正);
}
return(false);
}

但是我会停下来,否则我会创建另一个jquery插件。

Using jquery I've added a change handler to a form. This works when any input is changed BUT only if the user manually changes an input and not when some other code changes the input.

Is there any way to detect if a form has changed even if its inputs are changed by code?

解决方案

Yes, there seems to be some confusion over this. In an ideal world you would expect the onchange event to happen whenever the inputs change but thats not what happens. I'm sure for good reasons to - maybe not.

One way I've overcome this obstacle is to capture the form state into a variable just after displaying it and then just before submitting it to check if the state has changed and to act accordingly.

An easy state to store is what the serialize function returns. An easy place to store the state is using the data functionality. Both serialize and data are available with jquery.

Of course you can use other different forms of state (some form of hash) or storage for this state (standard global variable for example).

Here is some prototype code:

If your form id is 'xform' then you can call the following code when the form has displayed:

$('#xform').data('serialize',$('#xform').serialize());

And then, when you need to check, for example just before a button submit you can use:

if($('#xform').serialize()!=$('#xform').data('serialize')){
    // Form has changed!!!
}

You could wrap all this up into a copy & paste javascript snippet that will give you a formHasChanged() function to call wherever you need it (NOT TESTED):

$(function() {
    $('#xform').data('serialize',$('#xform').serialize());
});
function formHasChanged(){
    if($('#xform').serialize()!=$('#xform').data('serialize')){
        return(true);
    }
    return(false);
}

But I'll stop here otherwise I'll create yet another jquery plugin.

这篇关于找出HTML表单是否发生了变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆