jay jay - 4 months ago 6
jQuery Question

How to create a remove button to remove one div at a time using JQUERY?

<div class= "button">
<button id="More" type="submit">Add more Parameters</button>
<button id="Remove" type="submit">Remove Parameters</button>
</div>

<script>
var count = 2;
$('#More').click(function(){
if (count==11) {
}
else {
$("div2").append("<div class='fieldBlock'><fieldset><legend>Parameter " + count + "</legend><label >Parameter Name: </label><select type=text id='name" + count + "' name='name' ><option></option></select></br></br><label >Address: </label><select type=text id='address" + count + "' name='address' ><option></option></select></br></br><label >Data Size: </label> </br><select type=text id='size" + count + "' name='size' ><option></option></select> </select> </br> </br><label >Write Data: </label> </br><input type=text id='data" + count + "' name='data' style='width: 14em;'></br> </br></fieldset></div>");
count++;
}
});

$('#Remove').click(function(){
....
});


Can someone show me how if a user clicks on a remove button, the div that was appended can be removed? Also if user appends multiple times, I want the remove button to only remove one div at a time.

Answer

If you convert the id of Remove button to class, you may add the remove button to each new created div:

$(function () {
  var count = 2;
  $('#More').on('click', function(){
    if (count==11) {

    }
    else {
      $(".div2").append("<div class='fieldBlock'><fieldset><legend>Parameter " + count + "</legend><label >Parameter Name: </label><select  type=text id='name" + count + "'  name='name' ><option></option></select></br></br><label >Address: </label><select  type=text id='address" + count + "'  name='address' ><option></option></select></br></br><label  >Data Size: </label> </br><select  type=text id='size" + count + "'  name='size' ><option></option></select>  </select> </br> </br><label >Write Data: </label> </br><input  type=text id='data" + count + "'  name='data' style='width: 14em;'></br> </br><button class=\"Remove\" type=\"submit\">Remove Parameters</button></fieldset></div>");
      count++;
    }
  });

  $(document).on('click', '.Remove', function(e){
    $(this).closest('div.fieldBlock').remove();
    count--;
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<div class="div2">
    <div class= "button">
        <button id="More" type="submit">Add more Parameters</button>
    </div>
</div>