Generic way to detect if html form is edited

后端 未结 7 1064
悲&欢浪女
悲&欢浪女 2020-11-30 18:41

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 woul

相关标签:
7条回答
  • 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()) {
       // ...
    }
    
    0 讨论(0)
提交回复
热议问题