kaya new kaya new - 16 days ago 5
Javascript Question

javascript to remove dynamically added div

i have 3 textfield which i want to clone with one remove icon on add button click ...upto this my code works fine.

Now i want to remove the last 3 textfields of that particular div on remove button click...but my code removes all the dynamically added textfields of my form..

please help me to resolve this....



$('#add_exercise').on('click', function() {
$('#exercises').append('<div class="exercise"><input type="text" name="exercise[]"></div>');
$('#exercises').append('<div class="exercise"><input type="text" name="exercise[]"></div>');
$('#exercises').append('<div class="exercise"><input type="text" name="exercise[]"><button class="remove">x</button></div>');
return false;
});

$('#exercises').on('click', '.remove', function() {
$(this).parents("#exercises").remove();
return false;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="exercises">
<div class="exercise">
<input type="text" name="exercise[]">
<input type="text" name="exercise[]">
<input type="text" name="exercise[]">
</div>
<button id="add_exercise">add exercise</button>
<button class="remove">x</button>
</fieldset>




Answer

The issue is with your use of .parents('#excercises') as this selects the top level container and removes it.

A better solution would be to wrap all the 3 inputs you append in their own div and then remove that using closest(), like this:

$('#add_exercise').on('click', function() {
  $('#exercises').append('<div class="exercise"><input type="text" name="exercise[]"><input type="text" name="exercise[]"><input type="text" name="exercise[]"><button type="button" class="remove">x</button></div>');
});

$('#exercises').on('click', '.remove', function() {
  $(this).closest(".exercise").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="exercises">
  <div class="exercise">
    <input type="text" name="exercise[]">
    <input type="text" name="exercise[]">
    <input type="text" name="exercise[]">
    <button type="button" class="remove">x</button>
  </div>
  <button type="button" id="add_exercise">add exercise</button>
</fieldset>

Note that I added type="button" to your <button> elements as it would make sense for them not to submit any parent form elements.

Comments