John John
John John

Reputation: 1

Unable to delete tbody for a table using Jquery

I have the following table inside my markup:-

<table id="tablelist" border="1">

       <thead>
        <tr>
    </tr>
    </thead>
       <tbody></tbody>
       </table>

and i am building the above table using the following Java script which will be fired when the user click on a link:-

function getprocesslist(result) {
        $('#tablelist tbody').remove();

    var str = 'Total Number Of Processes:- ' + result.total.toString();
        $('#total').text(str.toString());

        var str1 = '<tr><th>' + 'Process Name' + '</th><th>' + 'Process Requestor ID' + '</th><th>' + 'Process State' + ' </th><th>' + 'Process Start Date' + ' </th><th>' + 'Process Due Date' + ' </th></tr>';
        $('#tablelist tr:last').after(str1);
    $.each(result.data, function (key, val) {
        var str2 = '<tr><td>' + val.name + '</td><td>' + val.requesterId + '</td><td>' + val.state + '</td><td>' + val.startedTime + '</td><td>' + val.due + '</td></tr>';

        $('#tablelist tr:last').after(str2);

    });
   }

But the problem is that when the user clicks multiple time on the link the new data will be shown under the old table instead of removing the old data. i think the problme with my code is that on the first clink the <tbody></tbody> is remove and i can not reference it again using Jquery ? any idea on how i can solve this problem?

BR

Upvotes: 1

Views: 7194

Answers (2)

st3inn
st3inn

Reputation: 1596

You are removing the tbody, then adding everything to the table head. Instead, empty the head and the body and append the content in the right places:

function getprocesslist(result) {
    $('#tablelist tbody, #tablelist thead').empty();

    var str = 'Total Number Of Processes:- ' + result.total.toString();
    $('#total').text(str.toString());

    var str1 = '<tr><th>' + 'Process Name' + '</th><th>' + 'Process Requestor ID' + '</th><th>' + 'Process State' + ' </th><th>' + 'Process Start Date' + ' </th><th>' + 'Process Due Date' + ' </th></tr>';
    $('#tablelist thead').append(str1);

    $.each(result.data, function (key, val) {
        var str2 = '<tr><td>' + val.name + '</td><td>' + val.requesterId + '</td><td>' + val.state + '</td><td>' + val.startedTime + '</td><td>' + val.due + '</td></tr>';
        $('#tablelist tbody').append(str2);
    });
}​

Upvotes: 2

yodog
yodog

Reputation: 6232

add the tbody again.

$('#tablelist').append('<tbody></tbody>');

Upvotes: 1

Related Questions