Martney Acha
Martney Acha

Reputation: 3002

Jquery Removing the added Input Text

I Need to add remove the added textbox via jquery, adding Input Text is working fine but when I remove it, it doesnt remove. here is my code: any idea ?

Jquery Code

$(document).ready(function() {
            var max_fields      = 10; //maximum input boxes allowed
            var wrapper         = $(".input_fields_wrap"); //Fields wrapper
            var add_button      = $(".add_field_button"); //Add button ID

        var x = 1; //initlal text box count
        $(add_button).click(function(e){ //on add input button click
            e.preventDefault();
            if(x < max_fields){ //max input box allowed
                x++; //text box increment
                $(wrapper).append('<div><div class="container"><div class="row"><div class="col-lg-3"><input type="text" name="mytime[]" class="form-control input-sm"/></div><div class="col-lg-3"><input type="text" name="mytext[]" class="form-control" /></div><div class="col-lg-3"><a href="#" class="remove_field">Remove</a></div></div></div></div>'); //add input box
            }
        });

        $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
            e.preventDefault(); $(this).parent('div').remove(); x--;
        })
    });

HTML Code:

<div class="input_fields_wrap">
                 </div>

Upvotes: 1

Views: 47

Answers (1)

gaetanoM
gaetanoM

Reputation: 42044

The point is:

 $(this).parent('div').remove();

Change this line with:

$(this).closest('div.container').remove();

From jQuery:

.closest( selector )

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

The snippet:

$(function () {
  var max_fields      = 10; //maximum input boxes allowed
  var wrapper         = $(".input_fields_wrap"); //Fields wrapper
  var add_button      = $(".add_field_button"); //Add button ID

  var x = 1; //initlal text box count
  $(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
      x++; //text box increment
      $(wrapper).append('<div><div class="container"><div class="row"><div class="col-lg-3"><input type="text" name="mytime[]" class="form-control input-sm"/></div><div class="col-lg-3"><input type="text" name="mytext[]" class="form-control" /></div><div class="col-lg-3"><a href="#" class="remove_field">Remove</a></div></div></div></div>'); //add input box
    }
  });

  $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault();
    $(this).closest('div.container').remove();
    x--;
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="add_field_button">Add input field</button>
<div class="input_fields_wrap">
</div>

Upvotes: 1

Related Questions