Dynamically creating Listviews and dynamically adding items to listview is one of the most frequently asked issue in jQueryMobile forums.

All dynamically added items needs to be enhanced to apply JQM styles.
Here is the rules.

  1. Use Listview(“refresh”) for adding new item(<LI>) to an existing Listview(<UL>).
  2. Use $(containerSelector).append($newlistmarkup).trigger(“create”) for adding a new Listview(UL).

Below code provides sample of

  • Dynamically add items to an existing listview.
  • Dynamically add a listview and then add items to it.

A Full Demo can be seen here

dynamicList.html

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
  
  <script>
    var i = 0;
  	function addListItem(flag) {
  		if (flag === 1) {
  			$("#listView1").append('<li><a href="#">List Item - ' + (++i) + '</a></li>').listview("refresh"); 
  		} else {
  			var container = $("#container1"), UL = container.find("#listView2");
  			if (UL.length) {
  				UL.append('<li><a href="#">List Item - ' + (++i) + '</a></li>').listview("refresh");
  			} else {
  				container.append('<ul data-role="listview" id="listView2"><li><a href="#">List Item - ' + (++i) + '</a></li></ul>').trigger("create");
  			} 
  		}
  	} 
  </script>
<title>JS Bin</title>
</head>
<body> 
   <div data-role="page" id="home">
        <div data-role="header">
            <h1>Dynamic Lists</h1>
        </div>
        <div data-role="content"> 
			<div style="width:200px;float:left;margin-left:60px"> 
				<ul data-role="listview" id="listView1">
					<li><a href="#">Acura</a></li>
					<li><a href="#">Audi</a></li>
					<li><a href="#">BMW</a></li>
					<li><a href="#">Cadillac</a></li>
					<li><a href="#">Ferrari</a></li>
				</ul> 
				<div style="height:50px;padding:20px">Above is a static list. Click below button to add an item.</div>
				<input type="button" onclick="addListItem(1)" value="dynamicItem(LI)"/>
            </div>
			<div style="width:250px;float:left;margin-left:60px"> 
				<div style="width:240px;" id="container1">
				
				</div>
				<div style="height:50px;padding:20px">Click below button to add a Dynamic listview and item. If listview not exist it will add one.</div> 
				<input type="button" onclick="addListItem(2)" value="dynamicItem(LI)"/>
            </div>
        </div> 
    </div>
</body>  
</html>