j3ffz j3ffz - 6 months ago 153
Javascript Question

jQuery Replace Table Body Contents

I seem to be having problems with my jQuery script. I would like to replace the current "tbody" contents with the new "tbody" contents. Currently it is just continues to add to the current data instead of removing the old data and inserting the new data. Any ideas?

Here is my code:

function getData(action,searchVal) {
$.get('ajax.php',{action:action,value:searchVal}, function(data){
var json = jQuery.parseJSON(data);
$(function () {
var content = '';
content += '<tbody>';
for (var i = 0; i < json.length; i++) {
content += '<tr id="' + json[i].ID + '">';
content += '<td><input id="check_' + json[i].ID + '" name="check_' + json[i].ID + '" type="checkbox" value="' + json[i].ID + '" autocomplete=OFF /></td>';
content += '<td>' + json[i].ID + '</td>';
content += '<td>' + json[i].Name + '</td>';
content += '<td>' + json[i].CountryCode + '</td>';
content += '<td>' + json[i].District + '</td>';
content += '<td>' + json[i].Population + '</td>';
content += '<td><a href="#" class="edit">Edit</a> <a href="#" class="delete">Delete</a></td>';
content += '</tr>';
}
content += '</tbody>';
$('table tbody').replaceWith(content);
});
});
};

Answer
function getData(action,searchVal) {    
    $.get('ajax.php',{action:action,value:searchVal}, function(data){
        var json = jQuery.parseJSON(data);
        $(function () {
            var content = '';
            //content += '<tbody>'; -- **superfluous**
            for (var i = 0; i < json.length; i++) {
            content += '<tr id="' + json[i].ID + '">';
            content += '<td><input id="check_' + json[i].ID + '" name="check_' + json[i].ID + '" type="checkbox" value="' + json[i].ID + '" autocomplete=OFF /></td>';
            content += '<td>' + json[i].ID + '</td>';
            content += '<td>' + json[i].Name + '</td>';
            content += '<td>' + json[i].CountryCode + '</td>';
            content += '<td>' + json[i].District + '</td>';
            content += '<td>' + json[i].Population + '</td>';
            content += '<td><a href="#" class="edit">Edit</a> <a href="#" class="delete">Delete</a></td>';
            content += '</tr>';
            }
           // content += '</tbody>';-- **superfluous**
            //$('table tbody').replaceWith(content);  **incorrect..**
             $('#myTable tbody').html(content);  // **better. give the table a ID, and replace**
       });  
    });
};

If you don't learn to correctly target your replace, you might end up with more than one table and replace the content of both. also since you are replacing the tbody contents, you can't add another level of tbody inside itself...