jonprasetyo
jonprasetyo

Reputation: 3586

How to remove elements once it was created by jquery

I am new to JQuery, I was wondering why my script is not working. I have been reading through the API and I did exactly what it says but I am still not getting what I was expecting. Please find the script below:

//To infinitely add images
$('.add_upload_image').on('click', function(){
    $('.upload_image').append('<input type="file" name="userfile[]"/><br/>');
});

//To remove the last child of the .upload_image
$('.remove_upload_image').on('click', function(){
    $('.upload_image input:last-child').remove();   
});

So I am sure you understand what I am trying to achieve. But basically, i have a text that says 'click to add more uploads' which is wrapped around with the .add_upload_image then when the user clicks on it, it adds the input element to the div class .upload_image. Works fine. However, when the user clicks on the 'click to remove' which is wrapped in .remove_upload_image and I am aiming at the last child of the .upload_image that is input and it is not removing.

What am I doing wrong here?

Many thanks in advance.

Upvotes: 2

Views: 77

Answers (2)

adeneo
adeneo

Reputation: 318182

You have to use :last, not :last-child ( the <br> element is the last child ):

$('.remove_upload_image').on('click', function(){
    $('.upload_image input:last').remove();   
});

You should probably remove the <br> element as well:

$('.remove_upload_image').on('click', function(){
    var el = $('.upload_image input:last');
    el.add(el.next('br')).remove();   
});

FIDDLE

Upvotes: 3

HIRA THAKUR
HIRA THAKUR

Reputation: 17757

 $('.upload_image').last().remove()

This should work.

Upvotes: 1

Related Questions