filippo90 filippo90 - 1 year ago 74
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">
<input id="name" type="text" name="name">
<input id="phone" type="number" name="phone">
<input id="city" type="text" name="city">
<input id="pcode" type="number" name="pcode">
<input id="note" type="text" name="note">

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 Source

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];