Pierre Nortje
Pierre Nortje

Reputation: 826

Adding JSON items to an HTML list using JQuery

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:

HTML after 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.

Upvotes: 2

Views: 15425

Answers (7)

Firos Shamsudeen
Firos Shamsudeen

Reputation: 71

If you are getting json data as a string from c#, then you need to parse to json in javascript.

function success(response) {
        $('.listboxclass').empty();
        $('.listboxclass').append('<option value="0">Select</option>');
        $.each(JSON.parse(response.d), function(i, obj) {
            $('.listboxclass').append('<option value="'+obj.id+'">'+obj.name+'</option>');
        });
    }

Here listboxclass is the classname of the listbox.

Here is the c# web method code which returns to ajax call.

[WebMethod]
public static string GetScreenList(string tId)
{
        return "[{\"id\":\"1\",\"name\":\"aaa\"},{\"id\":\"2\",\"name\":\"bbb\"}]";
}

Upvotes: 0

Mahesh singh chouhan
Mahesh singh chouhan

Reputation: 585

It will be work

Use json formate like this

{
    "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"
                }
            ]
        }
    ]
}

And correct your script like

$(document).ready(function () {
    $.getJSON('test.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=""><li class="name"><a href="#">' + item.name + '</a></li></ul>');
                $(".item:last").append(option_name);
            }); //$.each(...)
        }); //$.each(...)
    }); //$.getJSON
});     //$document 

I hope it will work.

Upvotes: 0

Raghbendra Nayak
Raghbendra Nayak

Reputation: 1646

As per my view you have to correct your JSON like:

{
    "product": [
        {
            "category": "Product 1",
            "items": ["Item 1-1","Item 1-2","Item 1-3"]
        },
        {
            "category": "Product 2",
            "items": ["Item 2-1","Item 2-2","Item 2-3"]
        },
        {
            "category": "Product 3",
            "items": ["Item 3-1", "Item 3-2","Item 3-3"]
        }
    ]
}

Then use below code I hope it will work for you:

<script>
$(document).ready(function () {
    $.getJSON('cwdata.json', function (cwData) {
        // Add the product categories
        $.each(cwData.product, function (i, product) {
            var option_cate = ('<li class="item'+i+'"><a href="#">' + product.category + '</a></li>');
            //alert(dump(product.items));
            //alert(product.items.length);
            $('#product_list').append(option_cate);
            // Add the product names
            for(var k=0;k<(product.items.length);k++){
                var option_name = ('<ul class="details"><li class="name"><a href="#">' + product.items[k] + '</a></li></ul>');
                //console.log(option_name);
                $(".item"+i).append(option_name);
            }
        }); //$.each(...)
    }); //$.getJSON
});     //$document  

</script>

Enjoy..... :)

Upvotes: 0

mridula
mridula

Reputation: 3281

Your json is wrong. For example:

Instead of

"items": [
            {
                "name": "Item 1.1",
                "name": "Item 1.2"
            }
        ]

It should be:

"items": [
            { "name": "Item 1.1" },
            { "name": "Item 1.2" }
         ]

Once that is corrected, you can change your code as -

$.each(cwData.product, function (i, product) {
    var option_cate = ('<li class="item"><a href="#">' + product.category + '</a></li>');
    $('#product_list').append(option_cate);
    var html = '<ul class="details">';

    $.each(product.items, function (i, item) {
        html += ('<li class="name"><a href="#">' + item.name + '</a></li>');
    }); 
    html += '</ul>'
    $('#product_list').append(html);
});

Upvotes: 2

Mohammed R. El-Khoudary
Mohammed R. El-Khoudary

Reputation: 1203

Ok.. I found several bugs in your solution..

First this is a modified working version

Now please note that your iteration:

$.each(product.items, function (i, item) {

Does not iterate properly because you have only one object inside the array so instead each item should be an independent object {"name": "bla bla bla"}

Second you append the items to ALL .item and add a UL for every item and that's also buggy.. please review my code and let me know if it helps.

Upvotes: 2

francadaval
francadaval

Reputation: 2481

This:

$(".item").append(option_name);

selects all html tags with class item. So you are appending the details to all existing <li class="item">.

Use a more especific selector to add the new content to your list element.

Upvotes: 0

alpakyol
alpakyol

Reputation: 2459

You are appending results to the class item which exists in three places. So it is appended to the three <li class="items">.

Try giving id to your <li> tags like <li id="product1">... instead <li class="item">

Upvotes: 0

Related Questions