1

I'm trying to remove all tbody rows and place with a new set however, my code below doesn't work. It removes them but I couldn't work out have to add new set of tbody set. I believe my output section is not ideal way of doing anyway. Please give me a hand.

I've checked these but to be honest, confused. - Adding rows to tbody of a table using jquery - jquery add and add

Thanks

HTML

<table class="table" id="add-new-yarn-table">
    <thead>
         <th>ID</th>
    </thead>

    <tr>
         <td>BELOW</td>
    </tr>

    <tbody class="filter-rows">
         <tr>
             <td>1</td>
         </tr>
    </tbody>
    <tbody class="filter-rows">
         <tr>
             <td>2</td>
         </tr>
    </tbody>
    <tbody class="filter-rows">
         <tr>
             <td>2</td>
         </tr>
    </tbody>
</table>

<span id='refreshTable()'>REMOVE OLD and ADD NEW SET</span>

JQUERY:

$('#refreshTable').click(function(event) {
    $.ajax({
        type    : 'POST',
        url     : 'hello.php',
        data    : {
            id  : '69'
        },
        success:function (data) {
                var output = '';

                $.each(data.data.records, function(index, value) {
                    var id = data.data.records[index]['id'];

                    output = output + '<tbody class="filter-rows">';
                    output = output + '<tr>';
                    output = output + '<td>' + id + '</td>';
                    output = output + '</tr>';
                    output = output + '</tbody>';
                });

                $('.filter-rows').remove();
                //ADD NEW ROWS SOMEWHRE HERE MAYBE
        }
    });
});
Community
  • 1
  • 1
BentCoder
  • 12,257
  • 22
  • 93
  • 165

3 Answers3

1

You don't have to remove the <tbody> at all, You can simply clear it using empty() and append() the new rows instead, as follows:

$('#refreshTable').click(function(event) {
$.ajax({
    type    : 'POST',
    url     : 'hello.php',
    data    : {
        id  : '69'
    },
    success:function (data) {
            var output = '';

            $.each(data.data.records, function(index, value) {
                var id = data.data.records[index]['id'];

                output +=  '<tr>';
                output +=  '<td>' + id + '</td>';
                output +=  '</tr>';
            });

            $('.filter-rows').empty().append(output);
    }
 });
});

In case if you actually must replace the existing <tbody> with new one, you can use replaceWith() in your original code as follows:

$('.filter-rows').replaceWith(output);
T J
  • 42,762
  • 13
  • 83
  • 138
0

Just add them after the thead:

$("#add-new-yarn-table thead").after(output);
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

Try this

Declare output as

var output = '<thead> <th>ID</th> </thead> <tr> <td>BELOW</td> </tr> ';

Then have the same $.each section.

Then set the innerHTML for table itself as the variable output.

acid_srvnn
  • 693
  • 8
  • 15