Question

I have a problem cloning a row in jQuery.

My JS:

<script>
  $(document).ready(function() {
    $('#addLine').click(function() {
      $('.data-line').last().clone({
      withDataAndEvents: false
    }).insertBefore('.data-line')();
    });                 
  });
</script>

My HTML:

<div class="form-group data-line"></div>
<a href="#" id="addLine"><i class="fa fa-plus"></i> Add</a>

My problem:

Each time i click on my link (#addLine), it clone the my row. But On second click, it will copie the two rows.

How to allow to copy only one row ?

Thanks.

Was it helpful?

Solution

Change your insertBefore selector:

$(document).ready(function() {
  $('#addLine').click(function() {
    $('.data-line').last().clone({
      withDataAndEvents: false
    }).insertBefore('.data-line:nth-child(1)');
  });                 
});

In your code you insert your cloned node before each element with class name .data-line.

Demo

OTHER TIPS

.insertBefore('.data-line') inserts the cloned element before every existing .data-line element. So it doesn't clone the two rows, it creates two clones of the last row and inserts each of them before every existing .data-line.

You can use .insertBefore('.data-line:first') instead instead, to only insert the clone before the first .data-line element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top