0

Seeking again your expert opinion on how to remove dynamic elements using jquery? Im currently working on a php page with forms with functionality to add and remove new section. Now im having issues when im trying to remove the newly added section using jquery. As the hyperlink doesn't get triggered.

HTML page:

  <div class="form-group">
    <label class="control-label col-md-4">File upload</label>
    <div class="col-md-6">
      <input type="file" />
      <textarea required placeholder="Description of the document" class="form-control" name="description-of-incident" id="description-of-incident" rows="2"></textarea>
      <div class="help-block with-errors"></div><br />
      <a href="javascript:void(0);" id="addanother">Add another</a>
    </div>
  </div>

<div id="container">
</div>

and this is the jquery i used:

  $(document).ready(function() {
      $('input[type="radio"]').click(function() {
             if($(this).attr('id') == 'peopleinvolvedyes') {
                  $('#involvement-section').show();
             }

             else {
                  $('#involvement-section').hide();
             }
         });

      $("#addanother").click(function(){
        $("#container").append('<div class="form-group"><label class="control-label col-md-4">File upload</label><div class="col-md-6"><input type="file" /><textarea required placeholder="Description of the document" class="form-control" name="description-of-incident" id="description-of-incident" rows="2"></textarea><div class="help-block with-errors"></div><a href="javascript:void(0);" class="remove-document-upload">Remove</a></div></div>');
      });

      $(".remove-document-upload").click(function(){
          alert("dasdasdas");
        //$(this).closest('.addanother').remove();
      });


  });

Whenever, i get click on the the 'Remove' hyperlink, the jquery function doesn't get triggered.

Comments and suggestions are high appreciated.

Thanks, Nhoyti

nhoyti
  • 1,615
  • 2
  • 26
  • 42

2 Answers2

0

FIDDLE

$(document).on('click', ".remove-document-upload", function() {
    alert("dasdasdas");

});

Use event delegation for dynamically created element.

.on() documentation is here

guradio
  • 15,524
  • 4
  • 36
  • 57
0
$(".remove-document-upload").click(function(){
    alert("dasdasdas");
    //$(this).closest('.addanother').remove();
});

Instead of this direct click use

$(document).on('click', '.remove-document-upload', function() {
    $(this).closest('.addanother').remove();
})

Here you need not to use direct document. you can use any selector which parent element has loaded at the time of document load

Manikanta Reddy
  • 849
  • 9
  • 23