0

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.

1
  • To find out why your handlers aren't working we'd need to see the JS since it also matters how the events are bound to the elements, e.g. Are you using document ready so that the DOM is atleast loaded, are you using specific classes in the $([selector]).on call? Commented Feb 23, 2016 at 13:32

2 Answers 2

1

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--;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the second option worked, I did try the first option myself. Solved both issues with this :)
1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.