0

I have this html:

    <div id="wrapper">
<div id="gamelist"></div>
</div>

and i want to place a unordered list in the gamelist div via Jquery.

                var gamenr = 0;
            $.each(response.payload, function(key, value) { 
                    //alert(key + ': ' + value);
                $('#gamelist').append("<ul id='"+gamenr+"' class='game'></ul>");

                $.each(value, function(key, value){
                    //alert(key +': ' + value);     
                    $("#gamelist").attr('id', gamenr).append("<li>"+value+"</li>");
                });
                gamenr++;
            });

The only thing that shows up, is the first value. gamenr is supposed to make a 'unique but not so beautifull' id.

I'd like to know why the rest of the values wont show up.

Thanks in advance,

Tim A

1
  • what do you have in response.payload? Commented Oct 31, 2012 at 12:01

4 Answers 4

2

You're changing the ID of #gamelist on the first iteration, and then you're trying to append to #gamelist in second iteration etc. which is an element that no longer exists, as you changed the ID in the first iteration :

var gamenr = 0;
$.each(response.payload, function(key, value) {
    var gamelist = $('<ul />', {id: 'a_'+(gamenr++), 'class':'game'});

    $.each(value, function(j, k) {
        var li = $('<li />', {text: k});
        gamelist.append(li);
    });

    $('#gamelist').append(gamelist);
});​
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your quick awnser. :)
0

You append <li> elements to the same <div> block but not to the appended <ul>:

var gamenr = 0;
$.each(response.payload, function(key, value) {
    $("#gamelist").append("<ul id='" + gamenr + "' class='game'></ul>");

    $.each(value, function(key, value) {
        $("#" + gamenr).append("<li>" + value + "</li>");
    });

    gamenr++;
});​

Comments

0

Look at this

$("#gamelist").attr('id', gamenr)

it will set the id for the element with id gamelist to the content of gamenr. This is not what you wanted. Try this instead

$('#'+gamenr)

Comments

0

just change the following code

$("#gamelist").attr('id', gamenr).append("<li>"+value+"</li>");

into next one

$("#gamelist ul[id='" + gamenr + "']").append("<li>"+value+"</li>");

6 Comments

Why not $("#" + gamenr)? It's faster.
it may be another elements with id = 0 or 1, etc. outside #gamelist
No, it can't be, otherwise the markup is invalid. Ids should be unique.
it' true if it just one page. but if it just a ajax module - you never can be sure about id=0 :)
If you are architect you should be sure :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.