-1

My web page has an "upload image" placeholder image by default. I want the user to be able to upload an image and have a javascript function call change the image "images/upload_wText.png" in the code below to whatever image file they chose. I've seen several similar questions (and answers) on SO but they don't exactly address what I'm trying to accomplish. I have tried tweaking the some of the solutions but nothing has worked. This is for a school programming assignment and we are not allowed to use jQuery. Any suggestions?

<div class="uploadImgContainer" id="uploadImgCont">
    <img src="images/upload_wText.png" alt="upload button"/>
</div>
<div class="uploadButtonContainer">
    <input type = "file" id="uploadImageBtn" onchange="uploadPetImg(this);"/>
</div>

javascript code:

function uploadPetImg(myImagePath) {
    document.getElementById("uploadImgCont").src = myImagePath;
}
gig6
  • 77
  • 1
  • 11
  • Post your javascript code. – NiK648 Feb 18 '18 at 06:40
  • I saw that another user trying to do something similar and they passed in "this" to the function. I thought it would be a file path but it doesn't appear to be the case. – gig6 Feb 18 '18 at 06:44
  • Refer this: [preview-an-image-before-it-is-uploaded](https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded) – NiK648 Feb 18 '18 at 09:47

1 Answers1

0

Two error
First, you try to set src to a <div> element.
Second, the way you try to get selected image file.

So, move id uploadImgCont to <img> tag and remove change attrib from <input> element.

<div class="uploadImgContainer">
   <img src="images/upload_wText.png" id="uploadImgCont" alt="Image"/>
</div>
<div class="uploadButtonContainer">
   <input type = "file" id="uploadImageBtn"/>
</div>

just add input listener within js like this, using only pure javascript

function uploadPetImg(imagePath){
   document.getElementById('uploadImgCont').src=imagePath;
}
window.onload=function(){
document.getElementById('uploadImageBtn').addEventListener('change',function(event){
    var imagePath=URL.createObjectURL(event.target.files[0]);
    uploadPetImg(imagePath);
});
}

Here's the fiddle(link)

Hope this help.