skip to Main Content

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

 </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

2

Answers


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

    document.getElementById('inputGroupFile01').addEventListener('change', function(event) {/*...*/});
    
    Login or Signup to reply.
  2. You are assigning two id to the same element. Specifically, you have id="inputGroupFile01" and id="inputimg" on the same element. Also, your event listener should be attached to the file input (inputGroupFile01), not the label (uploader).
    You have to,

    Ensure that each element has a unique id.
    Attach the event listener to the file input element, not the label.

    <div class="col-md-6">
      <div class="input-group mb-3" style="width: 40%;">
        <label class="input-group-text" for="inputGroupFile01">Upload</label>
        <input type="file" class="form-control" id="inputGroupFile01">
        <img src="profile.jpg" id="inputimg" class="img-fluid" alt="Placeholder image">
      </div>      
    </div>
    
    document.getElementById('inputGroupFile01').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);
      }
    });
    

    This will fix your issue

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search