Hardist
Hardist

Reputation: 1983

jQuery dynamic input fields

I am using this code to add and remove input fields: http://www.sanwebe.com/2013/03/addremove-input-fields-dynamically-with-jquery

Two issues I am facing that I haven't been able to solve:

$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>');

I want to append a div within a div like so (I am using bootstrap):

$(wrapper).append('<div class="form-group"><input type="text" class="form-control" "name="mytext[]" placeholder="test"><div class="input-group"><span class="input-group-addon"><span class="wb-close"></span></span></div></div>');

This works, obviously, but then my close function doesn't work anymore since it is trying to close the second div, not the "main" div (the <div class="form-group">. How would I be able to close the whole added div like in my example above?

Second issue, I am using the following as my close function:

<div class="input-group"><span class="input-group-addon"><span class="wb-close"></span></span></div>

But the close button doesn't work with the span icon wb-close, it just won't close. I tried adding the remove_field class to the span itself, but that also didn't work.

Upvotes: 0

Views: 1558

Answers (2)

Siva Kumar Siddam
Siva Kumar Siddam

Reputation: 154

Try this

$(function(){
$("#btn-add").click(function(){
  $("#wrapper").append('<div><input type="text" name="mytext[]"/><a href="#"              class="remove_field">Remove</a></div>');
      $("#wrapper").find("a").unbind("click");
     $("#wrapper").find("a").click(function(){
       $(this).parent().remove();      
     });      
  });
});


 <button id="btn-add">Add </button>
<div id="wrapper"></div>

Upvotes: 1

Rodrigo Kiguti
Rodrigo Kiguti

Reputation: 542

You need to change the selectors, because you changed the class name.

Try this:

$(wrapper).on("click", ".wb-close", function(e) {
    $(this).parent('.form-group').remove(); x--;
});

Or:

$(wrapper).on("click", ".wb-close", function(e) {
    $(this).parent().parent().parent().remove(); x--;
});

Upvotes: 1

Related Questions