Alex G Alex G - 5 months ago 19
Javascript Question

Cloning tbody breaks table columns

Got simple table, where I'm trying to clone and insert tbody element multiple times.

Issue: cloned cells don't align with the defined columns properly. (see jsfiddle)

Not sure what's going on here. I must use tables and tbody.

Any help is greatly appreciated.

Thanks.

<table class='assignees-form table border none'>
<thead>
<tr>
<th>Assignee</th>
<th>Start</th>
<th>Due</th>
</tr>
</thead>
<tbody class='assignee-template'>
<tr>
<td class='name'>Name</td>
<td class='start'>Start</td>
<td class='due'>Due</td>
</tr>
</tbody>
<tfoot>
<tr class='assignees-controls'>
<td><button class='add-button'>Add row</button></td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>

$('.add-button').click(function() {
$('.assignee-template').clone()
.removeClass('assignee-template').addClass('assignee')
.insertBefore('.assignees-controls')
.show();
});


FIDDLE

Answer

You are inserting cloned tbody inside the tfoot(before the tr inside tfoot), instead insert tbody before tfoot.

$('.add-button').click(function() {
    $('.assignee-template').clone()
            .removeClass('assignee-template').addClass('assignee')
            .insertBefore('tfoot')
            .show();
});

$('.add-button').click(function() {
  $('.assignee-template').clone()
    .removeClass('assignee-template').addClass('assignee')
    .insertBefore('tfoot')
    .show();
});
table {
  width: 50%
}
td {
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class='assignees-form table border none'>
  <thead>
    <tr>
      <th>Assignee</th>
      <th>Start</th>
      <th>Due</th>
    </tr>
  </thead>
  <tbody class='assignee-template'>
    <tr>
      <td class='name'>Name</td>
      <td class='start'>Start</td>
      <td class='due'>Due</td>
    </tr>
  </tbody>
  <tfoot>
    <tr class='assignees-controls'>
      <td>
        <button class='add-button'>Add row</button>
      </td>
      <td></td>
      <td></td>
    </tr>
  </tfoot>
</table>

FYI : Also why should you need to clone the entire tbody? instead just clone the first tr and append it to the tbody.