Add <li> to <ul> with for loop in jquery mobile

Mark Kamyszek picture Mark Kamyszek · Apr 9, 2013 · Viewed 8k times · Source

I'm using $.get() in my application to retrieve a list of facility names. I then want to insert them as list items in jquery mobile to an already existing . When I add a single element in the html, it looks ok, but when I use a for loop, the result doesn't have any of the styling effects.

http://jsfiddle.net/mkamyszek/YDFZ3/1/

<div data-role="page">
            <div data-role="header">
                <h1>My Title</h1>
            </div><!-- /header -->

            <div data-role="content">
                <ul data-role="listview" data-inset="true" data-filter="true" id="fieldList">
                    <li>Test</li>
                </ul>
            </div><!-- /content -->

        </div><!-- /page -->

The loop outputs the right information, but for some reason the styles don't apply when I user a loop:

for (i=0; i<=5; i++){
$("ul").append("<li>something" + i + "</li>");

}

Answer

Gajotres picture Gajotres · Apr 9, 2013

That is because you need to restyle listview after new content has been added.

Do it like this:

$('#listviewID').listview('refresh');

Sometimes when listview is generated dynamically it will require you to initilaize it before it can be styled, so in that case use this:

$('#listviewID').listview().listview('refresh');

Working example: http://jsfiddle.net/Gajotres/LrAyE/

And this is a working example out of your example: http://jsfiddle.net/Gajotres/HuKab/