3

When I try to use a html content inserted dynamically by append(htmlString) method in a page, the click event is not trigged. When I try to use the same html content normally, the click event is trigged.

$('#slc_field').change(function(event){
    $('#add_fields').removeClass("d-none");
    remove_link = "<a href='#' id="+this.value+" class='del_field text-danger' title='Remover item'> (x)</a>";
    html_field = " <div class='form-group col-md-4'>" +
                   "<label for='level_systemx'>Sistema de arranjo "+ remove_link +" </label> " +
                   "<textarea class='form-control' id='level_systemx' name='level_systemx' cols='250' rows='5'></textarea>" +
                  "</div>"
    $('#form_fields').append(html_field)
});

$('.del_field').click(function(event){
    $(event.target.parentNode.parentNode).remove()

});

Is it possible to trigger the click event on a html inserted by the append method?

Wesin Alves
  • 371
  • 1
  • 3
  • 13

3 Answers3

3

You can do like this also,

 $(document).on('click', '.del_field',function(event){
    $(event.target.parentNode.parentNode).remove();
});
Mohammad Raheem
  • 1,131
  • 1
  • 13
  • 23
2

You have to use event delegation.

$('body').click('on', '.del_field', function(event){
    $(event.target.parentNode.parentNode).remove()
});
giggi__
  • 1,793
  • 1
  • 11
  • 12
  • 1
    When you Append anything dynamically , then you have to trigger event within given Scope, either you can use document, body or any high level dom element – Mohammad Raheem Mar 28 '18 at 12:04
-1

The syntax for click event seems to be incorrect. You need to swap click keyword with that of on. The correct syntax should look like the one as below:

$('.del_field').on('click', function (event) {
    $(event.target.parentNode.parentNode).remove()
});
Shashank
  • 2,010
  • 2
  • 18
  • 38
  • Syntax is correct, your event is depend on dom element whether it is there or not at the time of event firing, best is always append with your scope – Mohammad Raheem Mar 28 '18 at 13:10