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" }]}';
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)
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>
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.
Related
I'm passing name & email through URL parameters from a popup form like this
xyz.com?om_email=test%40test.com&om_name=Test
I need these two forms prefilled on xyz.com site
<p>
<input type="text" name="name">
<input type="email" name="email">
</p>
Can anyone please help?
More context would be nice, but try this:
I used a test URL string to allow the example to work, but on the actual site, replace params variable with the one that is commented, (hint: window.location.search) to extract the parameters from the URL.
There are different ways to do this, but I created an object from the parameter string then looped over the inputs and updated their value by matching the data object key to the input value name attribute.
Note: Be sure to run the JavaScript after the page loads.
var url = "xyz.com?om_email=test%40test.com&om_name=Test";
var params = "om_email=test%40test.com&om_name=Test".split("&");
//use this on the actual site to extract parameters from the url
//var params = window.location.search.slice(1).split("&");
//convert the params to an object
var data = params.reduce((obj, param) => {
var pair = param.split("=");
return { ...obj,
[pair[0].replace("om_", "")]: decodeURIComponent(pair[1])
}
}, {});
//console.log({data});
//insert values by matching input name to data object key
document.querySelectorAll("input").forEach(input => input.value = data[input.name]);
<p>
<input type="text" name="name">
<input type="email" name="email">
</p>
This is how to autofill a form using HTML5.
<input value="valuehere">
I am pretty new to using localStorage, so excuse my ignorance and the potential repetition of this question. I couldn't get any answer yet.
I have a form with a lot of input tags. I am storing their values in a var called data var data = document.querySelectorAll( "input" ).value;
when I do window.localStorage.setItem('data', JSON.stringify(data.value))
it stores data in the storage with a value of undefined.
I get that my var data isn't really catching all the user input values, but I couldn't figure out how to do it.
My intention is to make var data an object that stores other objects that have the values of the input fields. then push this data to the localStorage. WITH PURE JS
Try this code, it writes to localStorage and reads from it to console (stackoverflow insert code tool doesn't allow to work with localStorage, that is why the code is in different JS sandbox): https://plnkr.co/edit/0e1R1aDTneQ1RA0Dvasj?p=preview
code:
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
<script>
let data = document.querySelectorAll("input");
let formData=[];
console.log('data', data);
for(let i=0; i<data.length; i++){
formData.push({ name: data[i].name, value: data[i].value })
}
console.log("formData for localStorage", formData)
localStorage.setItem('formData', JSON.stringify(formData));
let output = localStorage.getItem('formData');
console.log('output', JSON.parse(output));
</script>
</body>
</html>
As noted in the comments, you need to loop over your inputs to get the values and then store them in localStorage. For example:
const inputs = document.querySelectorAll('input');
const data = [];
for (const input of inputs) {
data.push(input.value);
}
window.localStorage.setItem('data', data);
Also, if you are really trying to store the data as JSON (perhaps why you were trying to use JSON.stringify()), then you could do something like the following (although it would be better if your input elements had unique id or name values you could use as keys rather than just the index of the selected input as in the example below).
const inputs = document.querySelectorAll('input');
const data = {};
inputs.forEach((input, i) => {
data[i] = input.value;
});
window.localStorage.setItem('data', JSON.stringify(data));
I am building an full-stack application in where I have a form submitting data to one of my post routes. On this form, I have all of my input fields bundled into req.body.model, thanks to the fact that I can add a name attribute with square brackets around the key, like so name="model[height]".
This should equate to something like this:
model = {
height: //value,
weight: //value,
age: //value
}
However, I want one of the values to be an empty array so I can push URLS into the array, like so:
model = {
height: //value,
weight: //value,
age: //value,
urls: [//urls here]
}
Since you can automatically create an object using the name attribute, I was wondering if there was a way to create a nested array using the name attribute as well?
Code snippet
<form>
<input type="text" name="model[height]">
<input type="text" name="model[weight]">
<input type="text" name="model[age]">
// these 2 inputs would go into the urls key in the models object
<input type="text">
<input type="text">
<button>Submit</button>
</form>
Not sure if I worded this properly...but let me know if I can explain in further detail.
If you pass index next to the property you can create an array. Something like this
// these 2 inputs would go into the urls key in the models object
<input type="text" name="model[urls][0]">
<input type="text" name="model[urls][1]">
Not sure if I got what you are trying to do exactly, but it seems like you can first process the submitted data and then send the processed data to wherever you want to send it. It's a bit more verbose, but I feel like it may give you more flexibility when organising your data. So maybe you can do something like this:
html
<form name="model">
<input type="text" id="height">
<input type="text" id="weight">
<input type="text" id="age">
<input type="text" id="url1">
<input type="text" id="url2">
<button onclick="processForm()">Submit</button>
</form>
script
function processForm() {
let height = document.querySelector("#height").value;
let weight = document.querySelector("#weight").value;
let age = document.querySelector("#age").value;
let url1 = document.querySelector("#url1").value;
let url2 = document.querySelector("#url2").value;
let model = {
"height": height,
"weight": weight,
"age": age,
"url": [url1, url2]
}
// now you can send model object to where it is needed
}
I have multiple input fields under different headings:-
<label>User</label>
<input type="text" ng-model="a.arr.username" name="arr[0]"/>
<input type="text" ng-model="a.arr.userdob" name="arr[0]"/>
<input type="text" ng-model="a.arr.userpanNo" name="arr[0]"/>
<label>Employee</label>
<input type="text" ng-model="a.arr.empname" name="arr[1]"/>
<input type="text" ng-model="a.arr.empdob" name="arr[1]"/>
<input type="text" ng-model="a.arr.emppanNo" name="arr[1]"/>
<label>Daily Workers</label>
<input type="text" ng-model="a.arr.dwname" name="arr[2]"/>
<input type="text" ng-model="a.arr.dwdob" name="arr[2]"/>
<input type="text" ng-model="a.arr.dwpanNo" name="arr[2]"/>
I want to save above data in the format:- [{a.arr.username:any value},{a.arr.empname:any value},{a.arr.dwname:any value}]. But the structure I am getting is:- {a.arr.username:any value,a.arr.empname:any value,a.arr.dwname:any value}.
Is there any way to do this?
Where you are storing data you will have to store it like :
a.arr=[];
//here you have to define object for each index before making keys of it.
a.arr[i]={};
Try this
var arr=[]; arr.push({'a.arr.username':$scope.a.arr.username,{'a.arr.empname':$scope.a.arr.empname}})
Basically, you want to make your object as an array of it's properties. I suggest you to leave the code as it is and just add a code to make another controller property which will hold the array of those properties.
To get the array of properties, below code will help you:
var x = {username: "any value", empname: "any value", dwname: "any value"};
var newArr = [];
var properties = Object.keys(x);
for(var i=0;i<properties.length;i++){
newArr.push({});
newArr[newArr.length - 1][properties[i]] = x[properties[i]];
};
Let me know if you need to understand anything else regarding this.
Best Regards
I'm not sure how to write this JS, so ask for help here!
HTML
<div class="grid_18" id="reference_container">
<div class="grid_16">
<fieldset>
<legend>Website</legend>
<span class="grid_2">Person</span>
<input name="person" class = "grid_6" type="text" />
<span class="push_2">Year</span>
<input class="push_2" name="year" type="text" />
</fieldset>
</div>
<div class="grid_16">
<fieldset>
<legend>Newspaper</legend>
<span class="grid_2">Author</span>
<input name="author" type="text" />
<span class="push_4">Year</span>
<input class="push_4" name="year" type="text" />
</fieldset>
</div>
</div>
What I need is a list of JSON one for each fieldset. The result will look like this:
[
{type:"website" , person: "(Based on user input)", year: "(Based on user input)"},
{type:"Newspaper", author: "(Based on user input)", year: "(Based on user input)" }
]
(type is static, the content comes from legend, other fields are not the same)
One thing need to notice is that the field name is not static(person, author etc..), need to pick up from name attribute.
This looks challenge for me, hope who can help with this~
var json = JSON.stringify($('fieldset').map(function () {
var self = $(this);
var obj = {
type: self.children('legend').text()
};
// Find each input element with a name attribute, and add the name/val to the object
self.find('input[name]').each(function () {
obj[this.name] = this.value + " (Based on user input)";
});
// Return the object we've constructed
return obj;
}).get());
map: Executes the provided function on each matched element, and returns a new jQuery object whose elements are the returned value of the function for each element.
get: Returns the jQuery object as an array.
Be sure to include the JSON library from https://github.com/douglascrockford/JSON-js, to support browsers which do not include the JSON library.
I have a solution that doesn't require json2.js. It uses jQuery's serialize() method and replaces the query string characters with valid JSON delimiters instead:
var arr = [];
$("fieldset").each(function () {
var $this = $(this),
serialized = $this.children("input").serialize(),
type = $this.children("legend").text();
// Replace the jQuery-serialized content into valid JSON
serialized = serialized.replace(/([^=]+)=([^&]*)(&)?/g, function ($0, name, val, amp) {
return '"'+name+'":'+'"'+val+'"' + (amp ? "," : "");
});
// Add it to the array
arr.push('{"type":"'+type+'",'+serialized+'}');
});
// Join the array into a valid JSON string
var json = "[" + arr.join(",") + "]";
There's a working demo here: http://jsfiddle.net/AndyE/ASrKN/
Note that it doesn't re-decode the result (for instance, if the user input has characters that should be url-encoded), but you would probably want these to stay encoded if you're posting to the server anyway.