Created
November 7, 2017 03:35
-
-
Save jorgepinon/f86003fb2d202dd73a84c7a4f8540f25 to your computer and use it in GitHub Desktop.
javascript function to check if a form has inputs that have been changed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Determines if a form is dirty by comparing the current value of each element | |
* with its default value. Nicely done on StackOverflow: https://stackoverflow.com/a/155812/1558564 | |
* | |
* @param {Form} form the form to be checked. | |
* @return {Boolean} true if the form is dirty, false if it's not. | |
*/ | |
function formIsDirty(form) { | |
for (var i = 0; i < form.elements.length; i++) { | |
var element = form.elements[i]; | |
var type = element.type; | |
if (type == "checkbox" || type == "radio") { | |
if (element.checked != element.defaultChecked) { | |
return true; | |
} | |
} | |
else if (type == "hidden" || type == "password" || | |
type == "text" || type == "textarea" || type == "email") { | |
if (element.value != element.defaultValue) { | |
return true; | |
} | |
} | |
else if (type == "select-one" || type == "select-multiple") { | |
for (var j = 0; j < element.options.length; j++) { | |
if (element.options[j].selected != | |
element.options[j].defaultSelected) { | |
return true; | |
} | |
} | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment