Skip to content

Instantly share code, notes, and snippets.

@kolunar
Created April 24, 2017 15:56
Show Gist options
  • Save kolunar/709854b090d909badddaa53fb99ce471 to your computer and use it in GitHub Desktop.
Save kolunar/709854b090d909badddaa53fb99ce471 to your computer and use it in GitHub Desktop.
jQuery check if form dirty
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; // returning false from this callback will break the each looping
} 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
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment