andymoyle andymoyle - 2 months ago 14
jQuery Question

jQuery append not in order

I'm using append() to help parse some json in a cordova app. Here's he code snippet

renderRotaView: function() {
$('.tab-button').removeClass('active');
$('#rota-tab-button').addClass('active');
$('#title').html('Rota');
$('#rendered').html('<div id="content"><table>');
$.getJSON('https://www.thegatewaychurch.info/wp-admin/admin-ajax.php',{ action: "ca_rota", service_id: 1 }, function(data) {
$.each(data, function(arrayIndex, userObject){
$('#rendered').append('<tr><td>' + userObject.job+'</td><td>'+ userObject.people + '</td></tr>');
});

});
$('#rendered').append('</table></div>');
}


Which results in

<div id="rendered"><div id="content">
<table></table>
</div>
<tr><td>Trailer</td><td>#</td></tr>
<tr><td>Setup</td><td>#</td></tr>
<tr><td>Welcome </td><td>#</td></tr>
<tr><td>Hotspot</td><td>#</td></tr>
<tr><td>Worship Leader</td><td>#</td></tr>
<tr><td>Singers</td><td>#</td></tr>
<tr><td>PA</td><td>#</td></tr>
<tr><td>Preacher</td><td>#</td></tr>
<tr><td>Catering</td><td>#</td></tr>
<tr><td>Livewires 0-3s</td><td>#</td></tr>
<tr><td>Livewires 3+</td><td>#</td></tr>
<tr><td>Explorers Infant</td><td>#</td></tr>
<tr><td>Explorers Juniors</td><td>#</td></tr>
<tr><td>Youth</td><td>#</td></tr>
</div>


So the append inside the .getJSON is not in the middle. What am I doing wrong please?

Answer

It's becuase you are appending it within div $('#rendered'). Change this to $('#rendered table'). Use the below code

renderRotaView: function() {
        $('.tab-button').removeClass('active');
        $('#rota-tab-button').addClass('active');
        $('#title').html('Rota');
        $('#rendered').html('<div id="content"><table>');
        $.getJSON('https://www.thegatewaychurch.info/wp-admin/admin-ajax.php',{ action: "ca_rota", service_id: 1 }, function(data) {
                $.each(data, function(arrayIndex, userObject){
                        $('#rendered table').append('<tr><td>' + userObject.job+'</td><td>'+ userObject.people + '</td></tr>');
                });

        });
        $('#rendered').append('</table></div>');
    }