Trying to get value from JSON
file and add on click
on button depending on the value of the json data
JSON file
{
"Cars": [
{
"desc": "here are the cars",
"models": [
{ "model": "bmw", "available": false },
{ "model": "mercedes", "available": false },
{ "model": "anything", "available": true },
{ "model": "audi", "available": false }
]
},
{
"desc": "another list",
"models": [
{ "model": "aaa", "available": false },
{ "model": "bbb", "available": false },
{ "model": "ccc", "available": false },
{ "model": "ddd", "available": true }
]
}
]
}
Part of javascript code
function appendData(data) {
var mainContainer = document.getElementById("myData");
var div = document.createElement("div");
for (i in data.Cars) {
for (j in data.Cars[i].models) {
var btn = document.createElement("button");
btn.addEventListener("click", function () {
alert(j);
});
btn.innerHTML = data.Cars[i].models[j].model;
div.appendChild(btn);
mainContainer.appendChild(div);
}
}
}
When the iteration reach btn.addEventListener
the j
value always 3
I need to add onclick function
depends on the j
iteration