Problem to remove an img tag inside the array by image id

Asked

Viewed 89 times

0

I’m doing an image preview with image removal. In case I need to remove the selected element from within the array using the id of the img tag. I can already take the id to the function that will be removed, but I cannot access the image element by the id of the image that is inside the array.

Here is the code for analysis:

for (var i = 0, f; f = files[i]; i++) {

        // Only process image files.
          if (!f.type.match('image.*')) {
            continue;
          }

        var reader = new FileReader();

        reader.onload = function (e) {
            base64imgs.push("<img class='thumb' id='img_"+id+"' src='"+e.target.result+"' >");
        };

        reader.readAsDataURL(f);
    } 

$('#output_box_foto').append("<img class='thumb' id='img_"+id+"' src='"+URL.createObjectURL(files_show[i])+"' onclick='Remover("+id+")'>");

function Remover(id) {
    id_img_remove="#img_"+id;
    $(id_img_remove).remove(); 
    //Acima eu apenas removo visualmente a imagem, e abaixo seria o trecho de código que não sei como fazer para remover o elemento de dentro do meu array. Aqui no caso eu gostaria de remover o elemento IMG pelo Id dele de dentro do array
    base64imgs // Já tentei slice, preg...sem êxito
} 

1 answer

1


Friend,

The Base64 array contains strings and not objects, so I believe you need to search for text and not selector.

It would be something like that:

var meuarray = [
        '<img id="img1" src="img1.jpg" />',
        '<img id="img2" src="img2.jpg" />',
        '<img id="img3" src="img3.jpg" />'
    ];

    var index = -1;

    $(meuarray).each(function (i, item) {

        if (item.indexOf('id="img1"') > -1)
        {
            index = i;
        }
    });

    if (index > -1) {
        meuarray.splice(index, 1);
    }

    console.log(meuarray);

Additionally...

If you want to work with jQuery selectors, I suggest you create your objects with jQuery instead of append with text. For example this block:

$('#output_box_foto').append("<img class='thumb' id='img_"+id+"'src='"+URL.createObjectURL(files_show[i])+"' onclick='Remover("+id+")'>");

Would look like this:

var imgBoxFoto = $('<img>', {
    class: "thumb", 
    id: "meuid", 
    src:"minhaurl"
}).on("click", function(el){
    Remover(id);
});

$('#output_box_foto').append(imgBoxFoto);

Note that you can also replace the onclick attribute of html and register directly in the object, without your "id" and method name being exposed in html.

Transforming your text array (of img tags) into objects would look like this:

    //array de objetos jQuery
    var meuarray2 = [
        $('<img>', { id: 'img1', src: 'img1.jpg' }),
        $('<img>', { id: 'img2', src: 'img2.jpg' }),
        $('<img>', { id: 'img3', src: 'img3.jpg' })
    ];

    //Os objetos criados em memória no jQuery ficam com formato de function "n.fn.init[1]"
    //Precisa transformá-los em objetos referenciáveis com o array:
    meuarray2 = $(meuarray2).map(function () { return this.toArray(); });

    //usa o filter passando o id -- Também poderia ser qualquer seletor (classe, data, type, etc)
    var index = meuarray2.index($(meuarray2).filter('#img1'));

    //faz o splice para eliminar o valor:
    if (index > -1) {
        meuarray2.splice(index, 1);
    }

    console.log(meuarray2);
  • Hello Ericson, I understood perfectly what you meant, really it is a much better and more organized way, however, I only came up with a difficulty, I think maybe it is problem with the DOM, when I click on the images to check their ID, it always takes the last id. I put it exactly the way you sent me var imgBoxFoto = $('<img>', { class: "Thumb", id: "meuid", src:"minhaurl" }). on("click", Function(el){ Remove(id); });

  • In the case of the Remove(id) event, is the id parameter always the same? You can use date attributes to store values in the element like this: $('<img>', { class: "Thumb", id: "meuid", src:"minhaurl" }). data('id', 'meuid'). on("click", Function(el){ Remove($(el.currentTarget). data('id')); });

  • Our you are really amazing. It worked perfectly, did not know this date attribute. Thank you very much Ericson!

  • You could still take the menu id like this, without using date: Function(el){ Remove($(el.currentTarget).attr('id')); }

  • Ericson, just one more question when I create the array, as I do to get a value of the object, in case I try to do so selector = $('<img>', { class: "Thumb", id: "img_"+contador_img, src: e.target.result }); base64imgs.push(selector); ?

  • If you already have the object, just use jQuery attr: meuObjeto.attr('src'); If you are looking for the object inside the array: $(meuarray2). filter('#img1'). attr('src') If the filter returns more than one value, you need to go through the array: $(meuarray2). filter('#img1')[0]. attr('src')

  • I tried, but I couldn’t, both to get the value and to remove, I used your example and in Alert appears Object Object base64imgs = $(base64imgs). map(Function () { Return this.toArray(); }); var index = base64imgs.index($(base64imgs). filter(id); if (index > -1) { base64imgs.splice(index, 1); } Alert(base64imgs); // returns Object Object // Insert in this way selector = $('<img>', { class: "Thumb", id: "img_"+counter_img, src: e.target.result }); base64imgs.push(selector);

  • the base64imgs variable is an array, so in Alert it presents Object Object. To get the src value of a specific id, it could look like this: $(meuarray2). filter('#img1'). attr('src'); If you want all of them, you need one for: $(meuarray). each(Function(i, item){ Alert($(item). attr('src'')) })

  • tried again, played an id I know exists, but appeared Undefined

  • I’m not getting Ericson

  • I did, I’m sorry, it was my mistake.

  • @Fáonteiro Do not forget to, in addition to accepting the best answer, also give a upvote in the answer of the colleague who helped you! This contributes not only to those who have helped you but also to other people who may be seeking references that have a good reputation within the community. ;)

  • How do I do that?

  • It says I need to have 15 of reputation, I can’t upvote yet =(

Show 9 more comments

Browser other questions tagged

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