itvba
itvba

Reputation: 235

jQuery append clones multiple times

I'm struggling with this jQuery code. When i want to clone a div, the first time it clones good. It only clones one div. But when i click the clone button again it clones the div like 3 times. What am i doing wrong?

HTML:

 <div class="screens-duplicate">
   <div class="row">
     <div class="col-lg-12">
       <h2>Breedte en hoogte:</h2>
         <div class="form-group">
          <label for="usr">Breedte:</label>
            <select class="js-example-basic-single" name="selectWidth[]">
              <option>Voer een getal in..</option>
             </select>
           </div>
         </div>
       </div>
     </div>

 <div class="another">
  <!-- here comes the cloned divs !-->
 </div>



 <div class="row">
  <div class="col-lg-12">
    <button type="button" name="screens-duplicate-button" id="screens-duplicate-button" class="btn btn-success"><i class="fa fa-plus" aria-hidden="true"></i> Clone</button>
  </div>

JS:

$('#screens-duplicate-button').click(function () {
  $('select').select2('destroy');
  $('.screens-duplicate').clone().appendTo('.another');
  $('select').select2({ width: '100%' });
});

I have tried the following but that aint working.

$('.screens-duplicate:first').clone().appendTo('.another:last');

Upvotes: 3

Views: 2740

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

You need to do it like below:-

$('.screens-duplicate:first').clone().appendTo('.another');

Example:-

$(document).ready(function(){
  $('#screens-duplicate-button').click(function () {
    $('.screens-duplicate:first').clone().appendTo('.another');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="screens-duplicate">
   <div class="row">
     <div class="col-lg-12">
       <h2>Breedte en hoogte:</h2>
         <div class="form-group">
          <label for="usr">Breedte:</label>
            <select class="js-example-basic-single" name="selectWidth[]">
              <option>Voer een getal in..</option>
             </select>
           </div>
         </div>
       </div>
     </div>

 <div class="another">
  <!-- here comes the cloned divs !-->
 </div>



 <div class="row">
  <div class="col-lg-12">
    <button type="button" name="screens-duplicate-button" id="screens-duplicate-button" class="btn btn-success"><i class="fa fa-plus" aria-hidden="true"></i> Clone</button>
  </div>

Upvotes: 5

Related Questions