filippo90 filippo90 - 4 months ago 20
JSON Question

How to Fill a Form with Data from a JSON

I have two file, a JSON storing some data and a simple html form.

I want to fill the form with random data taken from a JSON. Those data should be relative to the same object.

My form looks like:

<form id="first_form">
Name:<br>
<input id="name" type="text" name="name">
<br>
Phone:<br>
<input id="phone" type="number" name="phone">
<br>
City:<br>
<input id="city" type="text" name="city">
<br>
Pcode:<br>
<input id="pcode" type="number" name="pcode">
Note:<br>
<input id="note" type="text" name="note">
<br>
</form>


My JSON looks like:

users: [
{
"name": "name1",
"phone": "111111111",
"address": "address1",
"city": "city1",
"pcap": 1111,
"note": ""
},
{
"name": "name2",
"phone": "222222222",
"address": "address2",
"city": "city2",
"pcap": 2222,
"note": ""
},
{
"name": "name3",
"phone": "333333333",
"address": "address3",
"city": "city3",
"pcap": 3333,
"note": ""
},
{
"name": "name4",
"phone": "44444444",
"address": "address4",
"city": "city4",
"pcap": 4444,
"note": ""
}
]


Is there a way to do so in a no-jQuery way?

Answer

I hope it is users = rather than users :. Also change id 'pcode' to 'pcap'

In that case you can use the following code

var indx = Math.floor(Math.random()*users.length);
var randUser = users[indx];

for(prop in randUser) {
  document.getElementById(prop).value = randUser[prop];
}