Search code examples
jquerycloneaddition

Remove an added element with jquery


Two things that I'm trying to accomplish. 1) Using the clone method I want the user to be able to add multiple text box items with a delete link adjacent to the text box, not below it like it is working now. 2). When clicking the 'delete' link I want to remove the parent list item and delete link. I've looked around for an answer but not coming up with one. Also, if a method better than clone would work, I'm open for suggestions and explanations.

My jsfiddle code:

$('#click').click(function(){
var clone = $('li:last').clone()
if(!clone.find('.del')[0]) clone.append('<a href="#" class="del">Delete</a>')

clone.appendTo('ul');
    });

$('ul').on('click', 'li .del', function(){
     $(this).closest('li').remove();
        });

Solution

  • See your updated fiddle http://jsfiddle.net/juanpastas/56wuv/17/

    Basically you need to handle events in elements not yet created:

    $('ul').on('click', 'li .del', function(){
    

    And in order to use this selector

    $(this).closest('li')
    

    You need to actually put $(this), i.e. .del elements inside li element

    var clone = $('li:last').clone().append('<a href="#" class="del">Delete</a>')
    clone.appendTo('ul');
    

    Update

    if(!clone.find('.del')[0]) clone.append('<a href="#" class="del">Delete</a>')
    
    clone.find('.del') // returns elements with del class inside the cloned element
    [0]                // gets the first element in these elements, undefined if no del elements found
    !                  // negates undefined, i.e. true,
    
    // so code enter if when there is no del element
    
    clone.append('<a...'  // append delete if there is no delete link