You can add data to the actual data structure by appending it to the employees
array like
dataobj.employees.push({"firstName":$('input[name=firstn]').val(),
"lastName":$('input[name=lastn]').val() });
Of course, this requires that the JSON was parsed into the dataobj in the first place. It must be serialized again if you want to send it by GET
. But it can be POST
ed directly as a data object!
You can of course also start with an empty array, initializing dataobj like
var dataobj={ employee: [] };
before the above uptdating command comes into action.
A very late edit ...
Just in case there should be multiple firstname / lastname input fields, then the following will do a "much better" job (as it will have a look at all fields and collect only those where at least one of the names is set):
var dataobj={employees:[]};
function shw(){
$('#out').text(JSON.stringify(dataobj).replace(/{/g,'\n{'));}
$(function(){
$('#clr').click(function(){dataobj.employees=[];shw()});
$('#go').click(function(){
var ln=$('input[name=lastn]').toArray(); // ln: JS-Array of DOM elements
$('input[name=firstn]').each(function(i,fn){ // for each fn DOM-element ...
var f=fn.value,l=ln[i].value; // get values as strings
if (f+l>'') dataobj.employees.push({firstName:f,lastName:l}); // push name object
});shw();})
shw();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="firstn" value="John"><input type="text" name="lastn" value="Doe"><br>
<input type="text" name="firstn" value="Anna"><input type="text" name="lastn" value="Smith"><br>
<input type="text" name="firstn" value="Peter"><input type="text" name="lastn" value="Jones">
<input type="button" id="go" value="append names">
<input type="button" id="clr" value="clear">
<pre id="out"></pre>