Remove dynamically created <div> on click

I am trying to execute <div>

on click. When I tried with help .live()

it shows me:

the object has no live () method

I am using jQuery version 1.9, so it live

was removed.

$(document).ready(function(){
    $('#addhelper').click(function(){
        $('div#containerr').append('<div class ="helpcont"><input type="text" name="helper_caption[]" class="input-large" placeholder="Caption">'+
      '<input type="text" name="helper_url" class="input-large" placeholder="Url">'+
      '<input type="text" name = "helper_source" class="input-large" placeholder="Source"><button class = "remove" type="button">remove</button></div>');
    });

    $("button.remove").on({
        click: function(){
            $(this).remove('div.helpcont');
        }
    });
});

      

+3


source to share


1 answer


$("#containerr").on('click', '.remove', function(){
  $(this).closest('.helpcont').remove();
});

      

#containerr

= dynamically adds the closest parent that is not

click

= event (you can add multiple events by separating them with spaces)



.remove

= the selector for which the event is fired


PS: Use type selectors #id

instead element#id

. IDs have to be unique anyway, so there is no need to do it in the slow way, forcing jQuery to fetch all DIV elements and then look for the one with the given ID.

+4


source







All Articles