-2

I want to create a JSON with only those input fields that are changed before submitting the form.

How can I keep each and every changed value in the form of JSON?

$(document).ready(function() {

    $('#save').click(saveChangedValues);

}



function saveChangedValues(e) {

    e.preventDefault();

    var fields = $( "#frmStudInfo :input" ).serializeArray();

    trackFormDataChanges(fields);


   //make a ajax call with json only with the changed fields

   $.ajax{(
   )}

}

var finalJSON = {};

function trackFormDataChanges(fields){

    $.each( fields, function( i, field ) {
        //create final json
    });
}
<form id="frmStudInfo">

    Name <input type="text" id="name" name="name" >
    Date <input type="date" id="bdate" name="bdate">
    ID <input type="number" id="stdID" name="stdID"> 
    <input type="submit" id="save" value="Save" /> 

 <form>
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Cosmic Badal
  • 13
  • 1
  • 8
  • 2
    on change, mark field dirty. Loop over dirty fields, create json, submit. – Kevin B Nov 29 '16 at 22:52
  • You mean an object. JSON is a string format, and unless you want to start manipulating strings to save data, that's the last thing you should worry about. Also, just use the answer(s) from [this question](http://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery?rq=1), then you just need to track the changes as you go. – Heretic Monkey Nov 29 '16 at 22:59

1 Answers1

0

You can do something like this:

var prevFields;
$("#save").click(function(e){
  e.preventDefault();
  var fields = $( "#frmStudInfo :input" ).serializeArray();
  var changedInputs;
  if(prevFields){
    changedInputs = fields.filter(function(v){
      prevValue = prevFields.find(val => val.name === v.name);
      return !prevValue || v.value !== prevValue.value;
    });
  }else{
    changedInputs = fields;
  }
  console.log("changed inputs", changedInputs);
  prevFields = fields;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="frmStudInfo">
Name <input type="text" id="name" name="name" >
Date <input type="date" id="bdate" name="bdate">
ID <input type="number" id="stdID" name="stdID"> 
<input id="save" type="submit" id="save" value="Save" /> 
</form>

The idea is to store the values of all the inputs at each save and use them at the next save to see which ones have changed.

Titus
  • 22,031
  • 1
  • 23
  • 33
  • Thanks Titus, That helped. – Cosmic Badal Nov 30 '16 at 15:02
  • My scenario has two different json. The oldJSON from database and new json from the form submit. I need to compare these two and get the edited field only. Both of these JSONs are of different format. **OldJSON ** --> ({"name":"USCIS","date":06/12/2016 .......}) **fields(variable in avove example)** --> ([object Object],[object Object].......) – Cosmic Badal Dec 06 '16 at 21:03