Corby Bender
Corby Bender

Reputation: 23

json data jquery.append formatting issue

I'm trying to build a menu for a mobile app (using jQuery Mobile). I have an .asp page that queries SQL to pull the menu items (one for now, represented below by json[0].CompanyName). It returns as JSON data. I want to append the value from SQL to the <ul> with ID "mylist". This works and appends the text inside json[0].CompanyName, but it does not have the formatting of the hard coded Item 1 and Item 2 of the menu. Why does the formatting from the CSS work for the two hard coded menu items, but not the dynamic one?

  <div data-role="content" data-theme="b">  
     <ul id="mylist" data-role="listview" data-inset="true" data-filter="true" >
     <li><a href="item1.html" >Hard Coded Menu Item 1</a></li>
     <li><a href="item2.html" >Hard Coded Menu Item 2</a></li>
        <script type="text/javascript">
            $(document).ready(function () {
                $.getJSON("getdata.asp", function (json) {
                    // alert(json[0].CompanyName);
                    $('#mylist').append('<li><a href="#">' + json[0].CompanyName + '</a>    </li>');
                });
            });
        </script> 
     </ul>
  </div>

Upvotes: 2

Views: 1824

Answers (1)

Jasper
Jasper

Reputation: 76003

You have to refresh the listview after you append to it:

        $(function () {
            $.getJSON("getdata.asp", function (json) {
                $('#mylist').append('<li><a href="#">' + json[0].CompanyName + '</a>    </li>').listview('refresh');
            });
        });

This will tell jQuery Mobile to re-initialize the listview element to add the proper CSS classes to the proper elements.

Documentation can be found here: http://jquerymobile.com/demos/1.0/docs/lists/docs-lists.html (At the bottom of the page is a section called Updating lists)

Sometimes you run into the situation where you're not sure if the listview will be initialized yet, you can use this if/then to work-around that issue:

var $myList = $('#myList');
if ($myList.hasClass('ui-listview')) {
    $myList.listview('refresh');
} else {
    $myList.listview();
}

Upvotes: 3

Related Questions