Javascript does not load pre image preview

Asked

Viewed 68 times

2

I am using the code below for image preview before the Submit command of an html form.

HTML

<div class="col-md-2">
    <form method="POST" enctype="multipart/form-data">
        <img src="<?php echo $iniConf['LOGO']; ?>" class="img-responsive img-rounded" id="newLogo">
        <input class="hidden" id="searchNewLogo" name="logo" type="file" accept="image/*">
        <button class="btn btn-default btn-xs btn-block" id="alterLogo">Alterar logo</button>
    </form>
</div>

JAVASCRIPT

$('#alterLogo').click(function() {                
    $("#searchNewLogo").click();
});

$("#searchNewLogo").change(function() { 
    readNewImage(this);               
});               

function readNewImage(input) { 

    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#newLogo').attr('src', e.target.result).hide().fadeIn();
        }
        reader.readAsDataURL(input.files[0]);                    
    }
};

There is a problem of not loading the image when the html elements are inside the form. If I remove the form the image is loaded correctly.

Could someone explain to me why this is happening and how to fix it?

1 answer

0


Whenever you place a button inside a form, its default behavior is to send data, ignoring any instruction that is posted after your click. So you just need to block that behavior, like:

$('#alterLogo').click(function(event) {                
    event.preventDefault();  //bloqueia o comportamento padrão do botão
    $("#searchNewLogo").click();
});
  • Carlos Fernando, really that was it! Thanks for the help!

  • 1

    @Henqsan, you’re welcome!

Browser other questions tagged

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