2

I am trying to populate a JQM ListView with a local JSON information. However, no list items are created. Any help would be appreciated. Here is my code:

JSON File Structure:

[
{
"name" : "test"
"calories" : "1000"
"fat" : "100"
"protein" : "100"
"carbohydrates" : "800"
},
{
"name" : "test2"
"calories" : "10000"
"fat" : "343"
"protein" : "3434"
"carbohydrates" : "4343"
}
]

HTML:

<div data-role="page" data-title="Search" id="searchPage">
      <ul data-role="listview" data-inset="true" id="searchFood">
      </ul>
</div>

JS:

(Updated)

$(document).on("pageinit", "#searchPage", function(){
  $.getJSON("../JS/food.json", function(data){
        var output = '';
        $.each(data, function(index, value){
         output += '<li><a href="#">' +data.name+ '</a></li>';
        });
        $('#searchFood').html(output).listview("refresh");
  });
});
2
  • $('#searchFood').html(output).listview("refresh"); Commented Feb 19, 2014 at 13:24
  • Thanks Omar - but still no list items appearing with those changes:/ I have updated the JS on the post to reflect your suggestions. Commented Feb 19, 2014 at 13:30

1 Answer 1

6

First of all, the return JSON array is wrong, values (properties) should be separated by commas.

var data = [{
    "name": "test",
        "calories": "1000",
        "fat": "100",
        "protein": "100",
        "carbohydrates": "800",
}, {
    "name": "test2",
        "calories": "10000",
        "fat": "343",
        "protein": "3434",
        "carbohydrates": "4343",
}];

Second mistake, you should read value object returned by $.each() function not data array.

$.each(data, function (index, value) {
  output += '<li><a href="#">' + value.name + '</a></li>';
});

jQueryMobile only enhances the page once when it is loaded. When new data is added dynamically to the page, jQueryMobile must be made aware of the data for the data to be enhanced.

After extracting data from JSON array, append them then refresh listview to restyle newly added elements.

$('#searchFood').html(output).listview("refresh");

Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.