CSS Apprentice CSS Apprentice - 6 months ago 3x
Javascript Question

How To Add A Row Of Table Cells Based On Current Number Of Columns

enter image description here

Explanation: When "Add Row" is clicked, I want a new

appended to the tablebody. Inside the row, I want
equal to the current number of columns.

Potential Time Saver: I believe the last line of my jQuery is the issue, because I was shooting blind on it.


<!-- onClick Button -->
<div id="addRow">Add Row</div>

<th colspan="2">Header</th>
<th colspan="2">Header</th>
<!-- etc... -->
<!-- etc... -->
<!-- When button is clicked, add a <tr> with <td> inside. -->
<!-- number of <td> = current column span total -->


function getMaxColCount($table) {
var maxCol = 0;

$table.find('tr').each(function(i,o) {
var colCount = 0;

$(o).find('td:not(.maxcols),th:not(.maxcols)').each(function(i,oo) {
var cc = Number($(oo).attr('colspan'));
if (cc) {
colCount += cc;
} else {
colCount += 1;

//assuming this bit is my issue, primarily the last line.
//How do I tell jQuery to add multiple <td></td> based on the maxCol value?
return maxCol;
var addTD = '<td></td>'
$('tbody').append('<tr>'addTd * maxCol'</tr>');

Column Counting jQuery Found in this thread.

jsFiddle: https://jsfiddle.net/CSS_Apprentice/wfd8uryv/2/


How about just cloning the last row? And remove whatever content was in the previous one.

        var newOne = $("table tr:last").clone();
        $("table tr:last td").text("");
        newOne.insertAfter("table tr:last");

Your fiddle