Sam Sam - 3 months ago 7
Javascript Question

collect form data of every time submit in json

I am using a code in which, when we submit the form, gets all form input field value in JSON format.

But I want to collect all time data i.e. every time we submit the form it should be collected and display result. In the present situation I am getting only one time submit:

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};


$(function() {
$('form').submit(function(e) {
var ks = $('#answer').val().split("\n");
var formData = $('form').serializeObject();
$.extend(formData, { answerss : ks});
var result = JSON.stringify(formData);
$("#result").html(result);
return false;
});
});


current output:

{
"question": "1+1",
"type": "checkbox",
"answer": "1\r\n2\r\n3\r\n4",
"mandatory": "yes",
"json_data": "",
"answerss": ["1", "2", "3", "4"]
}


https://jsfiddle.net/aw339kwo/6/

Answer

use an array say 'resultFormArray' and each time you submit push it to this array. i.e resultFormArray.push(formData) where formData is your obj having the current submited data. Now the resultFormArray will contain all your form datas.

 var resultFormArray=[ ];                                                                         
        $(function() {
            $('form').submit(function(e) {
                var ks = $('#answer').val().split("\n");
                var formData = $('form').serializeObject();
                $.extend(formData, { answerss : ks});                                            
                resultFormArray.push(formData); 
                console.log(resultFormArray) /*will have all the form  datas in this*/
              /*var result = JSON.stringify(formData);  
               $("#result").html(result);    */                                                               
              return false;
            }); 
        });