Friday, February 11, 2011

Dynamically create elements in jQuery Mobile

jQuery Mobile is excellent to build mobile website. That is, you generate the html page using server side script, PHP, ASP or JSP. Then jQuery render the page in client side's browser.

However, if you try to use it like traditional AJAX web apps, such as loading JSON result and append them in DOM, you will be in trouble, at least now (jQuery Mobile 1.0a2). I summarized some solutions to force jQuery Mobile to re-render widget.

1. List View

$.getJSON(postsLink, function(data) {        
     
     $("#postsTemplate").tmpl(data).appendTo( "#postsList" );
     
  $('ul').listview('refresh');
     
     });

2. Select Menu
var categoryOption="";
  $.getJSON(categoriesLink, function(data) { 
   for (key in data) {
    var current = data[key];
    
    categoryOption=''+categoryOption;
   }
   $("#category").html(categoryOption).selectmenu('refresh', true); 
  
      });

3. Check boxes

var tagsOption="";
  $.getJSON(tagsLink, function(data) {        
   for (key in data) {
    var current = data[key];
    
    tagsOption='  '+tagsOption;
   
   }
   
   var taghtml='
Tags:'+tagsOption; taghtml=taghtml+'
'; $(taghtml).insertAfter('#categoryDiv').page(); });

1 comments:

vinay said...

Hello,

I tried to do what you said, but its not working out, can you plz check into my code for drop down box ?

Attached the code : http://pastehtml.com/view/bg9z9jrd8.txt

Plz let me know ...

Thank you