Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Image Preview with Bootstrap, HTML + JS

I am attempting to make a system that allows the user to upload an image and then it will replace the already placeholder image with the uploaded image by the user, I have attempted the JavaScript code below, but it simply just does not display the image when I upload it, the website shows the uploaded image.

I have used Bootstrap to style my columns and make my image fluid.

Below is the block of code relating to my issue

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 </div>
    <div class="col-md-6">
      <div class="input-group mb-3" style="width: 40%;">
        <label class="input-group-text" for="inputGroupFile01" id="uploader">Upload</label>
        <input type="file" class="form-control" id="inputGroupFile01" id="inputimg">
        <img src="profile.jpg" class="img-fluid" alt="">
      </div>      
  </div>

HTML CODE ABOVE

JS CODE BELOW

document.getElementById('uploader').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('inputimg').src = e.target.result;
        };
        reader.readAsDataURL(file);
    }
});

Tried the JS code embedded above, I expected the placeholder image to be replaced by the image I uploaded, that did not happen and nothing actually happened

>Solution :

The solution is to add the event to the input rather than the label, like

document.getElementById('inputGroupFile01').addEventListener('change', function(event) {/*...*/});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading