YVS1102
YVS1102

Reputation: 2748

Cloning rows not cloning tr

I'm trying to cloning table row. But i'm only able cloning what inside it without the tr tag. Please check my script

$(".tr_clone_add").on('click', function() {
  $('.tr_clone').last().clone({
    withDataAndEvents: true
  }).insertBefore('.tr_clone_add:first');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<table class="table table-striped table-bordered" cellspacing="0" width="100%">

  <thead>
    <tr>
      <td>Hari</td>
    </tr>
  </thead>


  <tbody>
    <tr class="tr_clone">
      <td>
        <select id="dropdown" class="form-control" name="hari[]">
          <option>Senin</option>
          <option>Selasa</option>
          <option>Rabu</option>
          <option>Kamis</option>
          <option>Jumat</option>
        </select>

      </td>
    </tr>
  </tbody>
</table>

<input type="button" name="add" value="Tambah Baris" class="tr_clone_add">

How can i fix it? Sorry for my bad english.

Upvotes: 1

Views: 64

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337570

Firstly note that clone() accepts a boolean value as the first parameter, not an object.

Secondly your issue is because you're appending the tr element before the button, not inside the table. Instead, try using appendTo('table tbody') like this:

$(".tr_clone_add").on('click', function() {
  $('.tr_clone').last().clone(true).appendTo('table tbody');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<table class="table table-striped table-bordered" cellspacing="0" width="100%">
  <thead>
    <tr>
      <td>Hari</td>
    </tr>
  </thead>
  <tbody>
    <tr class="tr_clone">
      <td>
        <select id="dropdown" class="form-control" name="hari[]">
          <option>Senin</option>
          <option>Selasa</option>
          <option>Rabu</option>
          <option>Kamis</option>
          <option>Jumat</option>
        </select>
      </td>
    </tr>
  </tbody>
</table>

<input type="button" name="add" value="Tambah Baris" class="tr_clone_add">

Upvotes: 2

Related Questions