Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
how to remove cloned input fleld jQuery

I created a function to clone input files if the user clicked twice on the choose file button to prevent the field from clearing the previous uploaded images

$(function() {

 // Multiple images preview with JavaScript
var multiImgPreview = function(input, imgPreviewPlaceholder) {

    if (input.files) {
     $("#multipleImageUpload").on("change", function(e) {
        var filesAmount = input.files.length;

        for (i = 0; i < filesAmount; i++) {
            var reader = new FileReader();

            reader.onload = function(event) {
                $($.parseHTML("<span class=\"pip\">" + 
                "<br/><span id=\"remove_icon\">Remove</span>" +
                "<img src=\"" + event.target.result + "\" title=\"" + "\"/>" +
                "</span>")).appendTo(imgPreviewPlaceholder);
 
                $("#remove_icon").click(function(){
                   $(this).parent(".pip").remove();
                 }); 
            }

            reader.readAsDataURL(input.files[i]);
        }
      });
    }
};


$(document).on('click', '#multipleImageUpload', function() {
    
    // add to preview
    multiImgPreview(this, 'div.imgPreview');

    
    //clone
    
    var originalInput = $(this), cloned = originalInput.clone();
    
    // move
    originalInput.attr("id", Date.now());
    originalInput.removeClass('multipleImageUpload');
    originalInput.appendTo($('#multipleFilesPH'));
    
    cloned.attr("id", "multipleImageUpload");
    cloned.insertAfter($('#multipleFilesPH'));

    originalInput = null;
    cloned = null;

});
});  

the issue here is when the user clicks on remove button it only removes the image from the view and the uploaded file is not removed and is sent to the server. any Idea what I'm doing wrong here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are two basic ways to do this.

  1. Use .on() to bind to the dynamic element
  2. Store reference to the object in a Variable and assign click() callback to the object

Here is an example of the latter.

$(function() {

  // Multiple images preview with JavaScript
  var multiImgPreview = function(input, imgPreviewPlaceholder) {

    if (input.files) {
      $("#multipleImageUpload").on("change", function(e) {
        var filesAmount = input.files.length;

        $.each(input.files, function(i, file){
          var reader = new FileReader();

          reader.onload = function(event) {
            var pip = $("<span>", {
              class: "pip"
            }).appendTo(imgPreviewPlaceholder);
            var icon = $("<span>", {
              class: "remove_icon"
            }).html("Remove").insertAfter(pip);
            var img = $("<img>", {
              src: event.target.result,
              title: ""
            }).insertAfter(icon);
            
            icon.click(function() {
              $(this).parent(".pip").remove();
            });
          }

          reader.readAsDataURL(file);
        }
      });
    }
  };

  $(document).on('click', '#multipleImageUpload', function() {

    // add to preview
    multiImgPreview(this, 'div.imgPreview');

    //clone
    var originalInput = $(this),
      cloned = originalInput.clone();

    // move
    originalInput.attr("id", Date.now());
    originalInput.removeClass('multipleImageUpload');
    originalInput.appendTo($('#multipleFilesPH'));

    cloned.attr("id", "multipleImageUpload");
    cloned.insertAfter($('#multipleFilesPH'));

    originalInput = null;
    cloned = null;

  });
});

This uses the jQuery ability to create DOM elements on the fly from the provided string of raw HTML. See More.

If you want to bind a click callback to that specific element, you can store the resulting Object in a variable and use that to bind the event to that object alone.

I switched the attribute to Class as you will likely have more than 1 element with this ID, hence why it would not be Unique from other elements. You might end up with 3 or 4 elements with the same ID.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda