0

I was trying to generate a new form group by clicking the button. But after that all I can't remove selected group, because click event doesn't work. here is fiddle example: https://jsfiddle.net/f4v25ert/

    (function($) {
    'use strict';
    $(document).ready(function() {

    $('.add').on('click', function(e) {
      e.preventDefault();
      $('.groups').append('\
        <div class="form-group">\
          <input type="text">\
          <a href="#" id="remove-input">Remove</a>\
        </div>\
      ');
    });

    $('#remove-input').on('click', '.form-group', function(e) {
        e.preventDefault();
      $(this).parent('.form-group').remove();
    });

  });
    }(jQuery));
Vlad Ivanov
  • 111
  • 1
  • 7

2 Answers2

-1

You can't have more than one items having the same id on a web page. Use a class instead.

Also, for dynamic binding, you should use

$(document).on('event', 'selector', function(){
    /* your code here */
});

(function($) {
  'use strict';
  $(document).ready(function() {

    $('.add').on('click', function(e) {
      e.preventDefault();
      $('.groups').append('\
        <div class="form-group">\
          <input type="text">\
          <a href="#" id="remove-input" class="remove">Remove</a>\
        </div>\
      ');
    });

    $(document).on('click', '.remove', function(e) {
     e.preventDefault();
      $(this).prev().remove();
      $(this).remove();
    });

  });
}(jQuery));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="add">Add input</button>
<div class="groups">
  <div class="form-group"><input type="text"></div>
</div>
mrid
  • 5,782
  • 5
  • 28
  • 71
-1
// Here is your working code
(function($) {
  'use strict';
  $(document).ready(function() {

    $('.add').on('click', function(e) {
      e.preventDefault();
      $('.groups').append('\
        <div class="form-group">\
          <input type="text">\
          <a href="#" class="remove-input">Remove</a>\
        </div>\
      ');
    });

    $(document).on('click','.remove-input' , function(e) {

        e.preventDefault();
      $(this).closest('.form-group').remove();
    });

  });
}(jQuery));
Neel Gala
  • 2,350
  • 1
  • 19
  • 20