visualizarImg() is not defined at Htmlinputelement.onchange

Asked

Viewed 547 times

1

I’ve seen some similar topics, followed the recommendations and was unsuccessful, so I open up a new topic. This error occurs when I upload an image and at the time of displaying it this message appears. PS: I already checked the page imports and everything is ok.

HTML

                                <div class="form-group col-md-12" >
                                     <div class="form-group">
                                      <input type="file" id="file" onchange="visualizarImg();" />

                                      </div>
                                </div>
                                   <div class=" form-group col-md-6">
                                      <img id="imagemPromocao" src=""  class="img-responsive"  />   
                                   </div>
                                </div>

Javascript

window.onload = function() {
    function visualizarImg() {
        var preview = document.querySelectorAll('img').item(1);
        var file = document.querySelector('input[type=file]').files[0];
        var reader = new FileReader();

        reader.onloadend = function() {
            preview.src = reader.result;// carrega em base64 a img
        };

        if (file) {
            reader.readAsDataURL(file);
        } else {
            preview.src = "";
        }

    }
}

1 answer

2


Since the function is inside onload, it cannot be accessed by html. Either you put it off the onload or add an event inside the onload instead of the html event:

seuinput.addEventListener("input", function () {
    //aqui o código da função visualizarImg
}, false);
  • If I put off the onload I will have the following error : Cannot set property 'src' of null at FileReader.reader.onloadend

  • Then leave the function inside the onload and add the event also inside the onload.

Browser other questions tagged

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