检测HTML表单是否被编辑的通用方法 [英] Generic way to detect if html form is edited

查看:97
本文介绍了检测HTML表单是否被编辑的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标签的html表单。从一个标签导航到另一个标签时,即使数据没有变化,当前标签的数据也会持久(在数据库中)。



我想使只有在编辑表单时才进行持久性调用。该表单可以包含任何类型的控件。炫耀表单不一定要通过输入一些文本,但在日历控件中选择一个日期也是有条件的。



实现此目的的一种方法是在读取时显示表单只有默认模式,并有一个'编辑'按钮,如果用户点击编辑按钮,然后调用数据库(再一次,不管数据是否被修改,这是对当前存在的更好的改进)。



我想知道如何编写一个通用的javascript函数来检查是否有任何控件值已被修改?

解决方案

在纯JavaScript中,这不是一件容易的事情,但jQuery使它很容易做到:

 $(#myform:input)。change(function(){
$(#myform)。data(changed,true);
});

然后在保存之前,您可以检查它是否已更改:

  if($(#myform)。data(changed)){
//提交表单
}

在上面的例子中,表单的ID等于myform。



如果您需要多种形式的插件,您可以轻松将其转换为插件:

  $。 fn.extend({
trackChanges:function(){
$(:input,this).change(function(){
$(this.form).data(changed ,true);
));
}

isChanged:function(){
return this.data(changed);
}
});

然后您可以简单地说:

  $( #myForm会)trackChanges(); 

并检查表单是否已更改:

< $($code> if($(#myform)。isChanged()){
// ...
}


I have a tabbed html form. Upon navigating from one tab to the other, the current tab's data is persisted (on the DB) even if there is no change to the data.

I would like to make the persistence call only if the form is edited. The form can contain any kind of control. Dirtying the form need not be by typing some text but choosing a date in a calendar control would also qualify.

One way to achieve this would be to display the form in read-only mode by default and have an 'Edit' button and if the user clicks the edit button then the call to DB is made (once again, irrespective of whether data is modified. This is a better improvement to what is currently existing).

I would like to know how to write a generic javascript function that would check if any of the controls value has been modified ?

解决方案

In pure javascript, this would not be an easy task, but jQuery makes it very easy to do:

$("#myform :input").change(function() {
   $("#myform").data("changed",true);
});

Then before saving, you can check if it was changed:

if ($("#myform").data("changed")) {
   // submit the form
}

In the example above, the form has an id equal to "myform".

If you need this in many forms, you can easily turn it into a plugin:

$.fn.extend({
 trackChanges: function() {
   $(":input",this).change(function() {
      $(this.form).data("changed", true);
   });
 }
 ,
 isChanged: function() { 
   return this.data("changed"); 
 }
});

Then you can simply say:

$("#myform").trackChanges();

and check if a form has changed:

if ($("#myform").isChanged()) {
   // ...
}

这篇关于检测HTML表单是否被编辑的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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