rolodex
rolodex

Reputation: 530

jQuery nested list from JSON not working. [solved, but comes another]

I'm creating a nested nested nested list, but I'm having problem assigning my buffer inside a UL. I tried $('ul#lists').html(buffer) but it didn't print out...

JSON

{
"browse": [
    { 
        "name":"browse by state" , 
        "command":"state" }, 

    { 
        "name":"browse by equipment" , 
        "command":"equipment" }, 

    { 
        "name":"browse by brand" , 
        "command":"brand" }
]
}

HTML

<section id="browser">
        <ul id="lists"></ul>
</section>

JQuery

$(function(tree_click){
    $('ul#lists').on('click','.c',function(){
    var test = "";
    $(this).removeClass('c'); //To assign this event once

    $.get('scripts/list.json', function(result, status){    
        var buffer = "";
        $.each(result, function(i, val){            
            for(var i=0; i < val.length; i++){ 
            var item = val[i];
            buffer+="<li><a href='#' cmd='"+item.command+"'>"+item.name+"</a></li>";} 
        });
        $(e.target).parent().append(buffer);
    });
});
});

The problem is solved. I updated my question with the solution.

But now my list toggler isn't working.

I use this for the toggler,

$(function(toggle_list){
$("#lists").on('click','a', function() {
    return !($(this).parents("li:first").find("ul:first").slideToggle('fast'))
});
});

Any takes?

Upvotes: 0

Views: 99

Answers (2)

Snowburnt
Snowburnt

Reputation: 6922

change:

$('ul#lists').on('click','.c',function(){ 

to:

$('ul#lists').on('click','.c',function(e){

specify var buffer inside this function but before the $.get call.

To append to the clicked UL, go like this inside the click handler:

$(e.target).append(buffer);

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Assuming the click event is called and the ajax request is successful and it is returning an array, there is a problem with var item = val[i]; because val itself is the current item in the array.

$(function (tree_click) {
    $('#lists').on('click', '.c', function () {
        $(this).removeClass('c'); //To assign this event once

        $.get('scripts/list.json', function (result, status) {
            var buffer = $.map(result, function (item) {
                return "<li><a href='#' cmd='" + item.command + "'>" + item.name + "</a></li>";
            }).join('');
            $('#lists').html(buffer);
        });
    });
});

Upvotes: 0

Related Questions