Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent jQuery .remove() from deleting parent class

I have created an clone element function which can be viewed view demo here. When the reset button is pressed it removes all cloned item elements, however when attempting to add another item the item list, the 'NEW' added item are not visible with the DOM.

 $('#add-btn').on('click',function(){
    $('.list-items:first').clone().appendTo("#items").addClass('isVisible');
    $('#items-fields').val('');
})

// RESET BUTTON 
$('.reset').on('click', function(){
    if( $('.list-items').length != 1);
    $('.list-items:last').remove();
    event.preventDefault();
})
like image 679
NewKidOnTheBlock Avatar asked Oct 18 '22 19:10

NewKidOnTheBlock


2 Answers

Where you have your reset button change the code in your if statement to the following

$('.reset').on('click', function(){
    if($('.list-items').length > 1) {
        $('.list-items:last').remove();
    }
})

At the moment you have set your list-items the following way..

When a user clicks the delete button, if the number of  things with the class list-item does not equal 0, then remove the last list-item

You need to change it the code so it does the following:

When a user clicks the delete button, if the number of  things with the class list-item is greater than 1, then remove the last list-item
like image 85
NewBoy Avatar answered Nov 01 '22 14:11

NewBoy


You should replace this:

var eleClone = $('list-items').clone(true);

by this:

var eleClone = $('.list-items').clone(true);

You search for the element which 'id' is 'list-item' while you want to search for the element which class is 'list-items'.

like image 27
Pierre Michard Avatar answered Nov 01 '22 14:11

Pierre Michard