javascript 找出html表单是否已更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10311663/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:25:24  来源:igfitidea点击:

Find out if html form has changed

javascriptjqueryhtmlformsonchange

提问by kingsaul

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.

使用 jquery,我向表单添加了一个更改处理程序。这适用于任何输入更改但仅当用户手动更改输入而不是其他一些代码更改输入时。

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

有没有办法检测表单是否已更改,即使其输入已被代码更改?

回答by zaf

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.

是的,对此似乎有些困惑。在理想的世界中,您会期望只要输入发生变化就会发生 onchange 事件,但事实并非如此。我确信有充分的理由——也许不是。

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 serializeand dataare available with jquery.

一个易于存储的状态是序列化函数返回的状态。存储状态的一个简单位置是使用数据功能。这两个序列化数据都可以使用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:

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

$('#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):

您可以将所有这些打包成一个复制和粘贴的 javascript 片段,该片段将为您提供一个formHasChanged()可以在任何需要的地方调用的函数(未测试):

$(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.

但我会停在这里,否则我将创建另一个 jquery 插件。

回答by Corneliu

Serializing the form is certainly an option, but it will not work if:

序列化表单当然是一种选择,但在以下情况下它将不起作用:

  • you want to know which fields have changed
  • it only needs to check a subset of the fields
  • dynamically adding or removing fields.
  • 您想知道哪些字段发生了变化
  • 它只需要检查字段的子集
  • 动态添加或删除字段。

Fortunately, every form element has a default value associated with its object:

幸运的是,每个表单元素都有一个与其对象关联的默认值:

  • input, textarea : defaultValue
  • checkbox, radio : defaultChecked
  • select: defaultSelected
  • 输入,文本区域:默认值
  • 复选框,收音机:defaultChecked
  • 选择:默认选择

for ex: to ckeck if input or textarea has changed:

例如:检查输入或文本区域是否已更改:

var changed = false;
$(":text,textarea").each(function(){
    changed = this.value != this.defaultValue;
    return !changed; // return if at least one control has changed value
});

回答by gdoron is supporting Monica

Not in a regular way.

不是以常规方式。

You can change with input and then trigger the change event.

您可以随输入更改,然后触发更改事件。

$('#inputId').val('foo').trigger('change');

or with this:

或与此:

$('#inputId').val('foo').change();

回答by Xeltor

Here is what i did (i found my solution using zaf's answer)

这是我所做的(我使用 zaf 的答案找到了我的解决方案)

$("form").change(function() {
    $(this).data("changed","true");
});

$("input[type='submit']").click(function() {
    if($("form").data("changed") == "true") {
        var discard = confirm("Some unsaved changes. Discard them ?");
        if(!discard) return false;
    }
});

回答by AnthumChris

This is easily achieved in JavaScript without jQuery. initChangeDetection()can be called multiple times:

这在没有 jQuery 的 JavaScript 中很容易实现。initChangeDetection()可以多次调用:

function initChangeDetection(form) {
  Array.from(form).forEach(el => el.dataset.origValue = el.value);
}
function formHasChanges(form) {
  return Array.from(form).some(el => 'origValue' in el.dataset && el.dataset.origValue !== el.value);
}

Test on JS Bin

在 JS Bin 上测试



对于不支持新箭头/数组函数的旧浏览器:

function initChangeDetection(form) {
  for (var i=0; i<form.length; i++) {
    var el = form[i];
    el.dataset.origValue = el.value;
  }
}
function formHasChanges(form) {
  for (var i=0; i<form.length; i++) {
    var el = form[i];
    if ('origValue' in el.dataset && el.dataset.origValue !== el.value) {
      return true;
    }
  }
  return false;
}

回答by Stefan Rogin

Try onchangeattribute According to W3cit should trigger anytime the content of an element, the selection, or the checked state have changed.

Tryonchange属性根据W3c,它应该在元素的内容、选择或选中状态发生变化时随时触发。