0

enter image description here

Explanation: When "Add Row" is clicked, I want a new <tr></tr> appended to the tablebody. Inside the row, I want <td></td> 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.

HTML:

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

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

jQuery:

$('#addRow').click(function(){
  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/

Community
  • 1
  • 1
CSS Apprentice
  • 899
  • 1
  • 16
  • 29

1 Answers1

2

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

    $('#addRow').click(function(){
        var newOne = $("table tr:last").clone();
        $("table tr:last td").text("");
        newOne.insertAfter("table tr:last");
    });

Your fiddle

Mike B
  • 2,756
  • 2
  • 16
  • 28