eng_mazzy eng_mazzy - 4 months ago 7
JSON Question

Print json data in a table

I have wrote the following function but I'm pretty sure there is an error. This is the error when I try to execute this chunck of code

TypeError: 'undefined' is not a function (evaluating 'callback.apply( obj[ i ], args )')


Jquery function receive data json list correctlu

$("#result_times")
.find("tr")
.remove()
.end();

$("#result_times")
.find("table")
.each(data, function(){
$(this).append($("<tr>"));
$(this).append($("<td></td>")).text(data.airport_city_source);
$(this).append($("<td></td>")).text(data.airport_city_dest);
$(this).append($("<td></td>")).text((data.departure_date));
$(this).append($("<td></td>")).text((data.arrival_date));
$(this).append($("</tr>"));
});


this is the DOM

<div id='result_times'>

<table>


</table>


</div>


Can you suggest me where I wrong?

Answer

You are running each() on each table, so jQuery is expecting a function as the first argument to the each, not data. Also you are calling text() on the wrong element.

Run the each on the data by using $.each.

Working example:

Demo

$("#result_times")
    .find("tr")
    .remove()
    .end();

var table = $('#result_times table');

$.each(data, function(){
    table.append(
        $('<tr></tr>').append(
            $('<td></td>').text(this.airport_city_source),
            $('<td></td>').text(this.airport_city_dest),
            $('<td></td>').text(this.departure_date),
            $('<td></td>').text(this.arrival_date)
        )
    );
});
Comments