In jQuery, is there a simple way to test if any of a form's elements have changed?

假设我有一个表单,我有一个包含以下click()个事件的按钮:

$('#mybutton').click(function() {
  // Here is where is need to test
  if(/* FORM has changed */) {
     // Do something
  }
});

我如何测试表单自加载以来是否已更改?

推荐答案

你可以这样做:

$("form :input").change(function() {
  $(this).closest('form').data('changed', true);
});
$('#mybutton').click(function() {
  if($(this).closest('form').data('changed')) {
     //do something
  }
});

This rigs a change event handler to inputs in the form, if any of them change it uses .data() to set a changed value to true, then we just check for that value on the click, this assumes that #mybutton is inside the form (if not just replace $(this).closest('form') with $('#myForm')), but you could make it even more generic, like this:

$('.checkChangedbutton').click(function() {
  if($(this).closest('form').data('changed')) {
     //do something
  }
});

References: Updated

According to jQuery this is a filter to select all form controls.

http://api.jquery.com/input-selector/

The :input selector basically selects all form controls.

Jquery相关问答推荐

为什么函数没有进入

如何限制select2中的字符?

jQuery 或 JavaScript 中的$符号是什么意思?

如何在 bootstrap 模式关闭并重新打开时重置 bootstrap 模式?

如何使用jquery取消绑定所有事件

jQuery获取表单字段值

jQuery Select 一个具有某个类的div,它没有另一个类

如何在 Jquery 中将 delay() 与 show() 和 hide() 一起使用

如何获取 onclick 调用对象?

jQuery $.cookie 不是一个函数

使用 D3.js(IE、safari 和 chrome)创建 SVG 后,如何保存/导出 SVG 文件?

如果不是 jQuery,Javascript 中的美元符号是什么

我如何知道 jQuery 是否有待处理的 Ajax 请求?

如何使用 javascript (jquery) 将整数值添加到返回字符串的值中?

Backbone.js - 事件,知道点击了什么

如何使用 JQuery $.scrollTo() 函数滚动窗口

使用 JQuery 的黄色淡入淡出效果

你能在不影响历史的情况下使用哈希导航吗?

Drop 事件未在 chrome 中触发

使用 Ajax 下载并打开 PDF 文件