2

How to store data as JSON like a database, so that when a user registers the information should be stored in a variable?

Example:

My HTML form consists of input text fields firstname, lastname. Clicking the register button of the form should store the values of firstname and lastname in a variables.

How can I do this:

 var txt = '{"employees":[' +
   '{"firstName":"John","lastName":"Doe" },' +
    '{"firstName":"Anna","lastName":"Smith" },' +
     '{"firstName":"Peter","lastName":"Jones" }]}';
Henry Lynx
  • 1,099
  • 1
  • 19
  • 41
Joshna Gunturu
  • 161
  • 1
  • 2
  • 13

4 Answers4

2

Sounds like you want to go from values in HTML to a JSON string. Assuming <form> looks like this

<form>
    <input type="text" name="nm1[]"/><input type="text" name="nm2[]"/>
    <input type="text" name="nm1[]"/><input type="text" name="nm2[]"/>
</form>

You can use getElementsByName twice, build an Object and JSON.stringify it

var nm1 = document.getElementsByName('nm1[]'),
    nm2 = document.getElementsByName('nm2[]'),
    i, o = {
        employees: []
    };
for (i = 0; i < nm1.length; ++i) {
    if (nm1[i].value && nm2[i].value)
        o.employees.push({
            firstName: nm1[i].value,
            lastName: nm2[i].value
        });
}
JSON.stringify(o);

DEMO (open console)

Paul S.
  • 64,864
  • 9
  • 122
  • 138
1

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 POSTed 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>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

You can use the push method of array to push JSON data. This is shown here - appending-to-a-json-object. Before the data needs to be submitted (say to process.php), stringify it.

Community
  • 1
  • 1
Patt Mehta
  • 4,110
  • 1
  • 23
  • 47
0

Easily use Jquery

var jsonArray;
jsonArray.push($("#firstname").val();
jsonArray.push($("#lastname").val();
var myJsonString = JSON.stringify(jsonArray);
rainer zufall
  • 100
  • 2
  • 7
  • The only part that is jQuery is `$("...").val()`. Otherwise your code is full of syntax errors, runtime errors and uses confusing variable names (like `jsonArray`). If you would initialize `jsonArray` properly, then it would contain a normal JS array, not JSON. – Felix Kling Aug 26 '13 at 12:39
  • Looking at this solution again, almost two years later, I have to agree with Felix: it will not work. The first line needs to be at least `var jsonArray=[];` to be consistent with the rest. But even then all the names found (firstname and lastname alike) will be thrown together into this simple array. The input fields might not even be found if their `id` attributes don't hold the same values as their `name` attributes. OP only mentioned the `name` attributes. – Carsten Massmann Jul 03 '15 at 06:11