Checkbox con ListView jQuery Mobile AJAX

Carlitox en la Web

by Carlos Martinez

HTML

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<a href="#!">Cargar Lista</a>
<ul data-role="listview" data-inset="true">
</ul>

CSS

.ux-checkbox {
  padding-top: 25px !important;
}

JavaScript

/*
 * Si usamos AJAX para llenar la lista, debemos actualizarla
 * antes de cargar los input:
 * 
 * $("ul[data-role='listview']").empty();
 *
 * ... logica para llenar la lista ...
 *
 * $("ul[data-role='listview']").listview("refresh")
 * 
 * Una vez hecho esto entonces continuamos
 */
$("a").click(function(e){
	var $list = $("ul[data-role='listview']").empty();
  
  //Simulando data AJAX
	var elements = 
    "<li data-icon='false'>"+
    "  <a href='#'>"+
    "    <h2>OPCION A</h2>"+
    "    <p>Descripcion A</p>"+
    "  </a>"+
    "  <a class='ux-checkbox' href='#'></a>"+
    "</li>"+
    "<li data-icon='false'>"+
    "  <a href='#'>"+
    "    <h2>OPCION B</h2>"+
    "    <p>Descripcion B</p>"+
    "  </a>"+
    "  <a class='ux-checkbox' href='#'></a>"+
    "</li>"+
    "<li data-icon='false'>"+
    "  <a href='#'>"+
    "    <h2>OPCION C</h2>"+
    "    <p>Descripcion C</p>"+
    "  </a>"+
    "  <a class='ux-checkbox' href='#'></a>"+
    "</li>";
	
  //Cargamos los elementos y actualizamos el componente
  $list.html(elements).listview("refresh");
  
  //Agregamos los input
  $list.find('li').each(function(){
    $(this)
    	.find('.ux-checkbox')
      .removeClass("ui-btn-icon-notext ui-icon-carat-r")
      .html("<input type='checkbox'/>");
  });
  
  //Actualizamos cada elemento en la lista
  $list.enhanceWithin();
  
  //Ocultamos el enlace
  $(this).remove();
});