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?
Asked
Active
Viewed 3.8k times
10
-
1refer 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 Answers
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
-
-
In this list, there is no "selected" value. It is a display only list. Build it with **select** and **option** instead of **ul** and **li** if you want a selection list. – Jesse Chisholm Mar 23 '14 at 19:40
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 v
is 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