I am adding items from a JSON file using JQuery to an HTML page dynamically.
HTML:
<div id='cssmenu'>
<ul id='options'>
<li class='active'><a href='#'><span>Home</span></a>
<ul id='home'></ul></li>
<li class='has-sub'><a href='#'><span>Products</span></a>
<ul id='product_list'></ul></li>
<li class='has-sub'><a href='#'><span>Company</span></a>
<ul id='company'></ul></li>
<li class='has-sub'><a href='#'><span>Contact</span></a>
<ul id='contact'></ul></li>
</ul>
</div>
JQuery:
$(document).ready(function () {
$.getJSON('../JSON/cwdata.json', function (cwData) {
// Add the product categories
$.each(cwData.product, function (i, product) {
var option_cate = ('<li class="item"><a href="#">' + product.category + '</a></li>');
$('#product_list').append(option_cate);
// Add the product names
$.each(product.items, function (i, item) {
var option_name = ('<ul class="details" style="display: none;"><li class="name"><a href="#">' + item.name + '</a></li></ul>');
$(".item").append(option_name);
}); //$.each(...)
}); //$.each(...)
}); //$.getJSON
}); //$document
JSON(cwdata.json file):
{
"product": [
{
"category": "Product 1",
"items": [
{
"name": "Item 1.1",
"name": "Item 1.2"
}
]
},
{
"category": "Product 2",
"items": [
{
"name": "Item 2"
}
]
},
{
"category": "Product 3",
"items": [
{
"name": "Item 3"
}
]
}
]
}
The problem is the data is being added the wrong way. The HTML looks like this after the page has been loaded:
.
Item 1, Item 2 and Item 3 are being added to Product 1, whereas I only want all the "items" under "Product 1" to be in the the Product 1 list.
Basically:
Product 1
- Item 1.1
- Item 1.2
But I am getting:
Product 1
- Item 1.1
- Item 2
- Item 3
Any tips would be appreciated.