• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 817
  • Last Modified:

JQuery How to populate dynamic list items

Yeah, so I hope this question is not too vague.

Let's say I have a dynamic ordered html list which will be populated with JSON from the server, e.g. a list of user information.

The list item itself consists of other elements like address, phone etc (see below). Of course I don't know up front how many list items I will get and what the information inside the list items will be. So what I'd like to do is fill out the values inside the list item based on their id (e.g. addr1, addr2). In order to do this I would like to create a type of 'prototype' list item and then be able to use a JQuery selector to populate the li field values based on id and then add them to the <ol> element using JQuery.

Can you tell me what this JQuery concept is called and perhaps point me to a sample?

My prototype li item:
                        <li id="'+i+'"> \
                              <table> \
                                    <tr> \
                                        <td width="10%"><p id="addr1">blah</p></td> \
                                        <td width="10%"><p id="addr2">Appt 1234</p></td> \
                                        <td width="10%" id="phone1"><p>888-555-1212</p></td> \
                                    </tr> \
                              </table> \
                        </a></li>'
0
php-newbie
Asked:
php-newbie
1 Solution
 
Michel PlungjanIT ExpertCommented:
You cannot use ID since ID needs to be unique. Instead use class names and clone the object.

Something like

var listItem = $('<li> \
                              <table> \
                                    <tr> \
                                        <td width="10%"><p class="addr1"></p></td> \
                                        <td width="10%"><p class="addr2"></p></td> \
                                        <td width="10%" class="phone1"><p></p></td> \
                                    </tr> \
                              </table> \
                        </a></li>');
$.get('someJSON',function(data) {
  $.each(data,function(i,addr) {
    var addrItem = listItem.clone();
    addrItem.find(".addr1").html(addr.addr1);
    addrItem.find(".addr2").html(addr.addr2);
    addrItem.find(".phone1").html(addr.phone1);
    addrItem.appendTo("#container");
  });
}); 

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now