10

In my jQuery mobile app, I want to display the result from a web service in a list. How do I create the list dynamically?

Pang
  • 9,564
  • 146
  • 81
  • 122
selladurai
  • 6,491
  • 14
  • 56
  • 88
  • 1
    refer http://stackoverflow.com/questions/5048360/dynamically-creating-jquery-mobile-pages-using-jquery-templates and http://stackoverflow.com/questions/4039428/jquery-mobile-dynamically-creating-form-elements – Akshatha Mar 15 '11 at 06:30
  • can u suggest some other examples? – selladurai Mar 15 '11 at 06:28

2 Answers2

20
var arr = ["list", "items", "here"];
$("div").append("<ul></ul>");
for(var i in arr) {
    var li = "<li>";
    $("ul").append(li.concat(arr[i]))
}
Erik Sandberg
  • 486
  • 5
  • 14
17

Better yet,

$.each(
    a ,
    function(i,v) {
        $("#target_id").append("<li>" + v + "</li>") ;
    }
) ;

Where a is an Array of Objects for the list content, i is the index variable passed to the callback function by jQuery.each ($.each) and vis the value for that index.


For reference: http://api.jquery.com/jQuery.each/ .

FK82
  • 4,907
  • 4
  • 29
  • 42
  • I wouldn't call that "better"; the accepted answer is pure JS, without any dependencies like jQuery (which is needed less and less as JavaScript continues to mature). – Jeff Dickey May 13 '19 at 16:18
  • @JeffDickey First of all, the accepted answer also uses jQuery (note the `$("div").append(...)`). I also hope you realize that this post is from 2011 and that OP explicitely states that he's using jQuery. Just sayin' :D – FK82 May 13 '19 at 20:08