Reputation:
I have a form with the option for the user to select first, then upload an image. The selected image should be previewed in the image tag below.
My HTML setup (only the necessary part):
<div class="form-group">
<label for="">Image</label>
<input type="file" accept="image/*" name="image" id="selImg" class="form-control" onchange="showImage().call(this)">
<img src="#" id="imgPreview" style="display: none; height: 200px; width: 200px">
</div>
I have a script tag below this where I'm writing my function do render the selected image like below:
<script>
function showImage (){
if (this.files && this.files[0]){
let r = new FileReader();
r.onload = ((data) => {
let img = document.getElementById("imgPreview");
img.src = data.target.result;
img.style.display = "block";
});
r.readAsDataURL(this.files[0]);
}
}
// tried previously but still doesnt work
// function readURL(inputStr){
// if (inputStr.files && inputStr.files[0]){
// let fileReader = new FileReader();
// fileReader.onload = (data)=> {
// $('#imgPreview').attributes('src', data.target.result).width(100).height(100);
// }
// fileReader.readAsDataURL(inputStr.files[0]);
// }
// }
//
// $('#img').change( ()=>{
// console.log(`Image Clicked`);
// readURL(this);
// });
</script>
The uncommented code is not mine but froma tutorial - this tutorial but also doesn't work.
Can someone explain to me why the image is not displayed? Thanks a lot.
Upvotes: 0
Views: 1063
Reputation: 97672
call
is a method on a function. If you append ()
at the end of the function you will be operating on the return of the function and not the function itself.
Therefore your code should be
showImage.call(this)
Upvotes: 2