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?

2

2 Answers 2

20
var arr = ["list", "items", "here"];
$("div").append("<ul></ul>");
for(var i in arr) {
    var li = "<li>";
    $("ul").append(li.concat(arr[i]))
}
Sign up to request clarification or add additional context in comments.

2 Comments

In that list, how can I get the selected value?
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.
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/ .

2 Comments

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).
@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

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.