How do I know that a form input has changed? How do I know that a form input has changed? jquery jquery

How do I know that a form input has changed?


Resurrecting this old question because I thought of a simpler/better way. Instead of listening to events on the various inputs, you can serialize the initial form data, store it, and then serialize it again later and check if it's changed, like this:

var originalFormData = $('form#formId').serialize();function checkFormChanged() {    if(originalFormData !== $('form#formId').serialize()) {        //it's dirty!    }}

One additional advantage here is that if the user makes a change and then reverts it, this check will report the form as clean.


The html controls include a property that holds the original value. You could compare this value with the current value to see if there have been any changes.

function getHasChanges() {    var hasChanges = false;    $(":input:not(:button):not([type=hidden])").each(function () {        if ((this.type == "text" || this.type == "textarea" || this.type == "hidden") && this.defaultValue != this.value) {            hasChanges = true;            return false;             }        else {            if ((this.type == "radio" || this.type == "checkbox") && this.defaultChecked != this.checked) {                hasChanges = true;                return false;                 }            else {                if ((this.type == "select-one" || this.type == "select-multiple")) {                    for (var x = 0; x < this.length; x++) {                        if (this.options[x].selected != this.options[x].defaultSelected) {                            hasChanges = true;                            return false;                        }                    }                }            }        }    });    return hasChanges;}function acceptChanges() {    $(":input:not(:button):not([type=hidden])").each(function () {        if (this.type == "text" || this.type == "textarea" || this.type == "hidden") {            this.defaultValue = this.value;        }        if (this.type == "radio" || this.type == "checkbox") {            this.defaultChecked = this.checked;        }        if (this.type == "select-one" || this.type == "select-multiple") {            for (var x = 0; x < this.length; x++) {                this.options[x].defaultSelected = this.options[x].selected            }        }    });}


From jQuery Docs:

//This applies to whole form$('#formID').change(function() {  alert('Form changed!');});

And you could do like this to check only the inputs and have user notified, if they try to exit without saving changes.

var inputsChanged = false;$('#formID input').change(function() {  inputsChanged = true;});$(window).unload(function() {  if (inputsChanged === true) {    alert('Would you like to save your edits before exiting?');   }    });

jQuery API .change()