admin管理员组文章数量:1307665
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" }]}';
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" }]}';
Share
Improve this question
edited Jan 12, 2016 at 16:03
Henry Lynx
1,1291 gold badge20 silver badges42 bronze badges
asked Aug 26, 2013 at 12:23
Joshna GunturuJoshna Gunturu
1611 gold badge2 silver badges14 bronze badges
4
-
you can use
var json = JSON.parse(txt)
– Arun P Johny Commented Aug 26, 2013 at 12:24 - 2 @ArunPJohny I think OP is asking for the other direction – Paul S. Commented Aug 26, 2013 at 12:24
- Is there a reason you want to use JSON? You cannot really process it further since it is just text. A simple object or array would be more appropriate. – Felix Kling Commented Aug 26, 2013 at 12:38
- i did not have much knowledge on JSON can you please tell me a good source for it @ArunPJohny – Joshna Gunturu Commented Aug 26, 2013 at 12:40
4 Answers
Reset to default 2Sounds 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)
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 mand es 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./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>
Easily use Jquery
var jsonArray;
jsonArray.push($("#firstname").val();
jsonArray.push($("#lastname").val();
var myJsonString = JSON.stringify(jsonArray);
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.
本文标签: javascriptHow to store JSON in a variableStack Overflow
版权声明:本文标题:javascript - How to store JSON in a variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741847585a2400871.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论