Delete photo by clicking a link

Asked

Viewed 35 times

0

Some time ago, I got a question here on the website of how to show the photo by upload field. The code works correctly, but I need the customer to click on the link Rule out, photo disappear and clear the field input=file no refresh. See:

inserir a descrição da imagem aqui

The code I have is this:

<input type="file" name="Foto" class="form-control" id="fileUpload" placeholder="Foto">
<img id="imagem" src="#" alt="Preview da sua imagem" style="width: 130px; margin-top: 10px; display: none" class="img-thumbnail" />
<label id="excluir" style="margin-left: 50px; color: #00F; display: none">Excluir</label>

Jquery

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $("#imagem").attr('src', e.target.result);           
        }     
        reader.readAsDataURL(input.files[0]);         
    }
}

$("#fileUpload").change(function(){
    readURL(this);
    $("#imagem").css("display","block");
    $("#excluir").css("display","block");
});

1 answer

1


It’s very simple to just add the following line:

$("#excluir").click(function(){
    $("#fileUpload").val("");
    $("#imagem").css("display","none");
    $("#excluir").css("display","none");
});

So it will remove the input file value and hide the image again.

Complete code:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $("#imagem").attr('src', e.target.result);           
        }     
        reader.readAsDataURL(input.files[0]);         
    }
}

$("#fileUpload").change(function(){
    readURL(this);
    $("#imagem").css("display","block");
    $("#excluir").css("display","block");
});

$("#excluir").click(function(){
    $("#fileUpload").val("");
    $("#imagem").css("display","none");
    $("#excluir").css("display","none");
});

Example: https://jsfiddle.net/8xzqede5/

  • 1

    Perfect. Thank you very much Wictor Keys.

Browser other questions tagged

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