By 05/02/2014 15 Comments

How to check if the form is dirty in Javascript

What is a dirty form ?

  • When a user fill any registration form on the website and user enters information in the form, suddenly he click to another link in the website, at this time user gets a warning message something like “If you click that link you will lost your changes stay here ? close ?”
  • different websites prompt different warning messages

For this, following code will used. The function returns a Boolean value (true of false) based on whether the user has made any virtual changes to the HTML form of a website


- Determines if a form is dirty by comparing the current value of each element
- with its default value.
* @param {Form} form the form to be checked.
* @return {Boolean} true if the form is dirty, false
* otherwise.
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") {
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;
window.onbeforeunload = function(e) {
e = e || window.event; 
if (formIsDirty(document.forms["someForm"])) {
// For IE and Firefox
if (e) {
e.returnValue = "You have unsaved changes.";
// For Safari
return "You have unsaved changes.";


Posted in: JavaScript

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .