Tom Nolan
Tom Nolan

Reputation: 1957

How to add table columns and rows dynamically with the correct number of cells?

I'm looking to dynamically add rows and columns to a table, and I've gotten pretty far researching how to do this with jQuery. I've successfully, been able to add columns that have the correct number of rows and remove an ENTIRE row. What I have not been able to do is add a row with the CORRECT number of columns and remove an ENTIRE column (all rows gone!).

Here is the script I have so far:

jQuery(window).load( function($) {

// Add column function
jQuery('#ldrm-add-col').click(function() {
    jQuery('.ldrm thead tr').append('<th class="rb-top">Test</th>');
    jQuery('.ldrm tr:gt(0)').append('<td>Col</td>');
    console.log('autocomplete');
});

// Add row function
jQuery('#ldrm-add-row').click(function() {
    jQuery('.ldrm tbody').append('<tr><td class="remove-row"><span class="btn">Remove</span></td><td class="rb-left">Test</td><td>Test</td></tr>');
    console.log('autocomplete');
});

// Remove row function
jQuery(document).on('click','td.remove-row .btn', function() {
    jQuery(this).closest('tr').remove();
});

});

So, if I start with three columns and click add row, it works fine right now because it adds 3 rows. However, if I click add column and it appends a 4th column and then I click add row, there is a cell missing because the script doesn't know that another column was added.

http://jsfiddle.net/2kws0aLx/

Any suggestions on how I can improve the add row script to take into account any dynamically added columns?

Upvotes: 0

Views: 1829

Answers (1)

galitskyd
galitskyd

Reputation: 216

For your add row function you will need to account for how many columns that are currently in the table. I did a quick and dirty IIFE to show what I mean.

http://jsfiddle.net/2kws0aLx/1/

// Add row function
jQuery('#ldrm-add-row').click(function() {
    // -2 to account for the two empty th's at top left
    var numOfCol = $('thead th').length - 2; 
    jQuery('.ldrm tbody').append('<tr><td class="remove-row"><span class="btn">Remove</span></td><td class="rb-left">Test</td>' + (function() { var str = ''; for(var i=0; i < numOfCol; i++) { str += '<td>Test</td>'; } return str; })());
    console.log('autocomplete');
});

Upvotes: 1

Related Questions