how to create elements dynamically in HTML using JSON file

Issue

I want to create HTML elements dynamically using JSON file.

{"myObject": {
"JAVA": {
    "id": "JAVAsubj",
    "path": "json/data.json"
},
"C#": { 
    "id": "JAVAsubj",
    "path": "json/data1.json"
},
"C++": {
   "id": "JAVAsubj",
    "path": "json/data2.json"
}
}
}

This is my JSON file. i want to create HTML buttons dynamically. Buttons should be create like JAVA,C#,C++. if i add something next to C++ then that button should get created dynamically

Solution

You can try something like this FIDDLE

however, i changed the myObject to an array of json objects as follows:

var jsonObj = {"myObject":
 [
    {
     title: 'JAVA',
     id: "JAVAsubj",
     path: "json/data.json"
    },
    { 
    title: "C#",
    id: "JAVAsubj",
    path: "json/data1.json"
    },
    {
    title: "C++",
    id: "JAVAsubj",
    path: "json/data2.json"
    }
  ]
}


var count = Object.keys(jsonObj.myObject).length;
var container= document.getElementById('buttons'); // reference to containing elm
for(var i=0;i<count;i++){
var obj= jsonObj.myObject[i];
var button = "<input type='button' value="+obj.title+"></input>"
container.innerHTML+=button;
}

Answered By – T J

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.