YVS1102 YVS1102 - 4 months ago 8
Javascript Question

Append datatables success but thead section gone

I'm try to use

append
to fill my table. Please take a look

<table width="100%" id="tbltbl" class="asoy table table-bordered table-striped">
<thead>
<tr>
<th width="1%">No</th>
<th width="14%">Outlet</th>
<th width="14%">Leader</th>
<th width="14%">Chief</th>
<th width="14%">RM</th>
<th> Action </th>
</tr>
</thead>
</table>


for default my table look like this
enter image description here
I run the
onchange
method and i receive this

[{"OutletCode":"K-BDIP3","Description":"BANDUNG INDAH PLAZA 3","NipLeader":"0802400","NipRM":"0802678"
,"NipChief":"-"},{"OutletCode":"K-CMHM2","Description":"KIOS CIMAHI MALL 2","NipLeader":"0802400","NipRM"
:"0802678","NipChief":"-"},{"OutletCode":"K-TSPA3","Description":"TASIK PLAZA ASIA 3","NipLeader":"0802400"
,"NipRM":"0802678","NipChief":"-"},{"OutletCode":"K-BDCW2","Description":"KIOS BANDUNG CIWALK 2","NipLeader"
:"0802400","NipRM":"0802678","NipChief":"-"}]


then i append it

function byarea(){
$(".asoy").empty();
var area = $("#pilihanarea").val();
var tipe = $('#tipe').val();
var formUrl = "<?=base_url();?>arealeader/finddata";
var angka = 1;
$.ajax({
url: formUrl,
type: 'POST',
data: {tipe:tipe,area:area},
success: function(data, textStatus, jqXHR){
var newdata = JSON.parse(data);
$.each(newdata, function(key, val) {
$('.asoy').append('<tbody><tr> <td>'+ (angka++) +'</td>' +
'<td>' + val.OutletCode + '</td>' +
'<td>' + val.NipLeader + '</td>' +
'<td>' + val.NipChief +'</td>' +
'<td>' + val.NipRM +'</td>' +
'<td>----</td>' +
'</tr></tbody></thead>');
});
}
});
}


and my table look like this

enter image description here

It seems I'm loosing my
<thead>..</thead>
section. Any solution for this ? thanks in advance...

Answer

Create an empty <tbody class="asoy"></tbody> just before the closing </table> tag and remove the class "asoy" from the <table> tag. Then remove the <tbody> tags from your call to append().

At the moment, your $(".asoy").empty(); is removing the entire table contents but you only want to clear the body, not the headers. Creating a <tbody> tag solves that problem while still allowing your function to be re-entrant (i.e. you can run it again later and it won't duplicate the contents).

Comments