Image preview

Asked

Viewed 68 times

-3

When I change the image, the preview of the previous images does not disappear...

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

        reader.onload = function (e) {
            $img = $('<img/>').attr('src', e.target.result);
            $(input).after($img);
        }

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

function verificaMostraBotao() {
    $('input[type=file]').each(function(index){
        if ($('input[type=file]').eq(index).val() != "")
            $('.hide').show();
    });
}

$('body').on("change", "input[type=file]", function() {
    verificaMostraBotao();
    readURL(this);
});

$('.hide').on("click", function() {
    $(document.body).append($('<input />', {type: "file" }).change(verificaMostraBotao));
    $('.hide').hide();
});
img{
  width: 150px;
  height: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="campo">
    <label> Foto do Aluno <font color="red">*</font></label></label>
    <input name="arquivo" id="file" type="file" accept="image/*" />
    <img />
    <input type="button" class="hide" value="Adicionar outro">
</div>

How to solve?

  • I’m sorry if I asked you an inappropriate question... I saw there were only votes against... I’m new around here in the stack.

1 answer

0


I got. Stayed like this:

JS

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

                reader.onload = function (e) {
                    $('#blah')
                        .attr('src', e.target.result)
                        .width(150)
                        .height(150);
                };

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

HTML

    <div class="campo">
  <label> Foto do Aluno <font color="red">*</font></label></label>
<input name="arquivo" id="file" type="file" accept="image/*" onchange="readURL(this);" /><img id="blah" />
</div>

Browser other questions tagged

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