How to disable submit button in jQuery if form fields have not been modified?

本小妞迷上赌 提交于 2019-12-06 07:56:34

Use dirty state tracking. Attach a boolean value (e.g. IsDirty) to every input control and toggle it whenever the value changes. While submitting the form check if atleast one or more values have changed and then submit the form. Otherwise display an alert to the user.

Another solution is to call a common function whenever a controls value changes. In this function you can set a global variable (IsDirty) to true if something changed and also enable/disable the submit button.

var isDirty = false;

function SomethingChanged(){
     if( !isDirty ) isDirty = true;
     btnSubmit.disabled = !isDirty;
}

Generic Function for any control

Assumptions: Add the initial value of each control to an attribute "InitVal"

function SomethingChanged(control){
     if( control.value != control.InitVal )
          control.IsDirty = true;
     else
          control.IsDirty = false;
}

In the above function to make it generic you can have separate functions for each type of control like TextBoxChanged and DropDownChanged etc. But have the following two attributes on each control

  1. InitValue - Initial Value of the control
  2. IsDirty - Boolean value indicating that the control's value has changed

Just two steps:

  1. store a hash of all initial values in a javascript variable
  2. onchange of every input recalculates that hash and verifies it with the one stored. if it's the same, disable the submit button, if it's not, enable it.

Have a look at the validation plug-in.

I havent tested whats below :-) But is that what you mean ?

$(document).ready(function() {
    $("#myform :input").attr("init",$(this).val()).bind("change.dirty", function(evt) {
        if ($(this).val()!=$(this).attr("init")) $(this).addClass("dirty");
        else $(this).removeClass("dirty");
        $('#thebutton').attr("disabled",!$("#myform .dirty").size());
    });
});

*-pike

It should be possible to save the whole form object (either as it is, or by iterating with .each() and storing the data in a map), and then do the same onSubmit and compare both values.

You can use dirtyField plugin instead and set denoteDirtyForm: true. Now if your form has "dirtyForm" class means you have unsaved changes.

What you could do is setup a jquery script to scan the page on page load and check for a form, inventory the fields and their values, and then check against that input reference array whenever an input is updated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!