Take Image Separately with Jquery

Asked

Viewed 372 times

0

I have a problem that I think for you will be very simple to solve. I’ve set up an image preview and I need to remove each image separately, but I’m not getting it, I’m trying to get the id. The images are inside a div called output_box_photo. I created a counter to assign different id’s to each image.

Here is the code below:

for(var i=0;i<total_file;i++)
    {
        // Only process image files.
          if (!files_show[i].type.match('image.*')) {
            continue;
          }
        $('#output_box_foto').append("<img class='thumb' id='"+contador_img+"' src='"+URL.createObjectURL(files_show[i])+"'><br/><span class='remove'>Remover</span>").on('click', function() {
                id = $("#output_box_foto").find('img').attr('id');  
                alert(id);
        });
    }

1 answer

0


Use the onclick event in the span tag marked with the 'remove' class and create a function that receives the id of the image to be removed. Example (I adapted your code because I had no access to the values of some variables):

$(document).ready(function () {
    var total_file = 5;
    var contador_img = 0;

    for(var i=0;i<total_file;i++)
    {
        $('#output_box_foto').append("<img class='thumb' id='"+contador_img+"' src=''><br/><span class='remove' onclick='Remover("+contador_img+")'>Remover</span>");

        contador_img++;
    }
});

function Remover(id) {
    alert(id);
}

The functional test of the example can be checked here: https://jsfiddle.net/marcellalves/1my79wty/

  • Thank you very much Marcell, Problem solved!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.