0

I'm working on a feature where the user needs to be informed that there are unsaved changes in a form in case if they decide to navigate away from the page.

I am almost done but there's a tiny problem-

I am setting a boolean dirty on input change event.

The .change() event will detect any kind of change, as in it doesn't keep track of changes. For example, if an input field has the original value hello, which is modified to bye and back to hello, it will still set the dirty boolean.

Is there any way where I can take a backup of the form with initial values and then compare it with itself at every change event?

Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71

3 Answers3

0

You need a way to serialize the form data into a JSON object, and then you could either compare the JSON object by iterating the properties or by comparing the JSON.stringify values.

I have slightly modified the method of objectifying the form data from here in order to do this.

var form = document.getElementById("myForm");
var originalFormData = objectifyForm(form);
var originalFormDataString = JSON.stringify(originalFormData);

setInterval(function() {
  var formData = objectifyForm(form);
  var formDataString = JSON.stringify(formData);
  console.log("Form is dirty: " + (formDataString != originalFormDataString));
},1000);

function objectifyForm(formArray) {//serialize data function

  var returnArray = {};
  for (var i = 0; i < formArray.length; i++){
    returnArray[formArray[i]['id']] = formArray[i]['value'];
  }
  return returnArray;
}
<form id="myForm">

  <input id="myInput" value="test" type="text" />
</form>
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
0

You can do something like this. Remember this solution is just a sample. You have multiple input element, than use array/object to save there defaultValue.

 var defaultValue = document.getElementById("myText").defaultValue;//Get the default value

 var handleChange = function (){
    let value =  document.getElementById("myText").value;//get the current value
    if(defaultValue===value){
       console.log("dirty false")
    }else {
       console.log("Dirty True")
    }
 
 }
<input type="text" id="myText" value="abc" onkeyup="handleChange()">
Ved
  • 11,837
  • 5
  • 42
  • 60
-1

I think you can create a javascript empty initial_values = {} object. initialised it with the default values in the form of key:value pairs. and if dirty boolean is set, it can be used to compare later on.

Tomonso Ejang
  • 1,336
  • 3
  • 15
  • 27