Filipe Ferminiano Filipe Ferminiano - 10 months ago 41
HTML Question

Error on removing fields added dynamically

I'm trying to add 3 fields dynamically (2 text fields and 1 remove button). The add button is working fine. The problem is the remove function. It's only removing the remove button, but not the other 2 fields it should.

This is my html code:

<div class="col-lg-12">

<div class="field_wrapper form-group col-sm-12">
<div class="form-group col-sm-4">
<input type="text" name="id[]" value="" class="form-control"/>
<div class="form-group col-sm-4">
<input type="text" name="name[]" value="" class="form-control"/>
<div class="form-group col-sm-4">
<a href="javascript:void(0);" class="add_button btn btn-primary" title="Add field">Adicionar Valor</a>


This is the javascript:

<script type="text/javascript">
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
//var fieldHTML = '<div><input type="text" name="field_name[]" value=""/><a href="javascript:void(0);" class="remove_button btn btn-danger2" title="Remove field">Remover</a></div>'; //New input field html
var fieldHTML = '<div class="field_wrapper form-group col-sm-12"><div class="form-group col-sm-4"><input type="text" name="id[]" value="" class="form-control"/></div><div class="form-group col-sm-4"><input type="text" name="name[]" value="" class="form-control"/></div><div class="form-group col-sm-4"><a href="javascript:void(0);" class="remove_button btn btn-primary" title="Add field">Remover</a></div></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter

How can I fix this?

Answer Source

The problem is that you're removing the $(this).parent('div'), that is giving you the form-group of the button and not the intended .field_wrapper, what you can do instead is use the .closest('.field_wrapper') which will find the element you've added.

Check this fiddle, for more information.