I'm trying to parse json array with objects and use them to create multiple checkboxes. This is what I have:
JSON data:
[{
"ID": 1,
"Name": "Bacon",
"Description": "",
"Price": 0
}, {
"ID": 2,
"Name": "Beef",
"Description": "",
"Price": 0
}, {
"ID": 3,
"Name": "Chicken",
"Description": "",
"Price": 0
}, {
"ID": 4,
"Name": "Ham",
"Description": "",
"Price": 0
}]
In the JS code I have this:
success: function (data) {
var objects = JSON.stringify(data);
for (var key in objects) {
var checkBox = "<input type='checkbox' data-price='" + key.Price + "' name='" + key.Name + "' value='" + key.ID + "'/>" + key.Name + "<br/>";
$(checkBox).appendTo('#modifiersDiv');
};
$('#addModifiers').modal('show');
}
But the key object doesn't contain any data. My question is how I can do foreach loop and get the data I need and fetch that data in the checkbox properties.
parsedata[i].ID,data[i].Name, etc... Also, why are you callingJSON.stringify()? You want it to be a javascript array, not a string.datais in the success handler. If you use jQuery's ajax call properly, it should already be a javascript array and you can just directly iterate it as an array. Step 1, do aconsole.log(data)to see exactly what it is.