Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery clone copying form elements twice on button click

I am using jquery clone.

When i click on add button a single clone is created with above fields...upto this clone works fine

But when i click Add button twice it create three copy of clone...it create three copies and like that..

i want when i create add button it just create only one clone every time and when i click remove it remove last clone...

below is my code..

<fieldset id="exercises">
          <div class="exercise">  

          </div>
</fieldset>

<script>
$('#add_exercise').on('click', function() {  
  $("<div class='exercise address_box'><div class='box'></div></div>").appendTo('#exercises');
  $("#toaddress").clone().val("").appendTo(".box"); 
  $("#sender_name").clone().val("").appendTo(".box"); 
  $("#OrderMobileCountryCode").clone().val("").appendTo(".box"); 
  $("#sender_no").clone().val("").appendTo(".box"); 
  $("#presentation").clone().val("").appendTo(".box");
  $("<br><button type='button' class='orange_btn' id='add_exercise'>Remove</button>").appendTo('.box');
  $("<br>").appendTo('.box');
  $("<br>").appendTo('#exercises');          
});

$('#exercises').on('click', '.orange_btn', function() {
  $(this).closest(".exercise").remove();
});
</script>  
like image 612
parcel pik Avatar asked Nov 09 '22 05:11

parcel pik


1 Answers

Change id of dynamically added button from add_exercise to remove_exercise

 $("<br><button type='button' class='orange_btn' id='remove_exercise'>Remove</button>").appendTo('.box');

And change the remove button event as ,

$('#exercises').on('click', '#remove_exercise', function() {
  $(this).closest(".exercise").remove();
});

Because your code producing element with same id which in turn triggering events more than once.

Try this modified code,

<script>
$('#add_exercise').on('click', function() {  
  $("<div class='exercise address_box'><div class='box'></div></div>").appendTo('#exercises');
  $("#toaddress").clone().val("").appendTo(".box"); 
  $("#sender_name").clone().val("").appendTo(".box"); 
  $("#OrderMobileCountryCode").clone().val("").appendTo(".box"); 
  $("#sender_no").clone().val("").appendTo(".box"); 
  $("#presentation").clone().val("").appendTo(".box");
  $("<br><button type='button' class='orange_btn' id='remove_exercise'>Remove</button>").appendTo('.box');
  $("<br>").appendTo('.box');
  $("<br>").appendTo('#exercises');          
});

$('#exercises').on('click', '#remove_exercise', function() {
  $(this).closest(".exercise").remove();
});
</script>
like image 135
ScanQR Avatar answered Nov 14 '22 21:11

ScanQR