Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Replace Table Body Contents

Tags:

jquery

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);  
       });  
    });
};
like image 901
j3ffz Avatar asked Dec 15 '10 17:12

j3ffz


3 Answers

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...

like image 129
FatherStorm Avatar answered Oct 18 '22 03:10

FatherStorm


Probably doesn't help so long after the post, you've probably retired, but here's my 2 cents worth.

I remove the tbody from the target table like so. $("#table_contacts tbody").remove();

Then use the following code to build an array of items containing a table row and corresponding cells, which are then appended to a tbody element which is in turn appended to the target table. The grunt work building the table row is abstracted to a separate function, buildItemRow(), for the sake of clarity.

 $.getJSON(uri)
                // On success, 'data' contains a list of employees.
                .done(function (data) {
                    // build  table rows and cells for passed employee
                    $.each(data, function (key, item) {
                        items.push(buildItemRow(item));                        
                    });
                    $('<tbody/>', {
                        html: items.join('')
                    }).appendTo('#table_contacts');                   
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#messages').toggleClass('badmessage');
                    $('#messages').html('A system error occurred while processing the request: ' + err + '<br />' + 'System Message: ' + jqXHR.responseText);
                });
like image 3
Mad Dog Avatar answered Oct 18 '22 02:10

Mad Dog


this.find('tbody').empty().append(content);

Can be enough to make it work if the correct table is passed.

Otherwise, get a little designer and have customisation like this:

var UDT = {
    proc : function(selector, settings) {
        // settings - set defaults
        var config = {
            'sortable':     false,
            'pagination':   false,
            'action':       'get',
            'searchVal':    'location'
        };
        if ( settings ){$.extend(config, settings);}
        var obj = $(selector);

        $.get('ajax.php',{action:action,value:searchVal}, UDT.sortShowData(data,obj));
        if (config.sortable) {obj.children('thead').find('th').addClass('sort');}
        if (config.pagination) {UDT.pageTable(obj);}
    },
    sortShowData : function(data,obj) {
        var json = jQuery.parseJSON(data);
        var content = '';
        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>';
        }
        obj.find('tbody').empty().append(content);
    },
    pageTable : function(obj) {
        // get content region for table height, tr height - work out how many rows can fit etc
        // else maxrows value
        // create tfoot content and append/replace to table
    }
};
// call for UpDateTable
UDT.proc($(##target_table##),{sortable:true, pagination:true, ...});

btw - adlibbed code... should work, but battery warning kicking in.

like image 2
greg.arnott Avatar answered Oct 18 '22 04:10

greg.arnott