Search code examples
javascripthtmlinputdynamicdefault-value

How to get value of input type = file and display it on a dynamically created image?


I have the following code:

function displayImg() {
  let fileUpload = document.getElementById("fileUpload").value;
  let container document.getElementById("container");
  container.innerHTML = `<img src="fileUpload">`
  
}
<input type = file id = "fileUpload" accept = "image/*">
<button onclick = "displayImg()">Click to show</button>
<div id="container"></div>

I want it so that the user can input the file into the file Input field and it is placed into the source of a dynamically-created image upon button click. How do I do this?


Solution

  • You can try this

    <html>
    <body>
    
    <input type = file id = "fileUpload" accept = "image/*">
    <button onclick = "displayImg()">Click to show</button>
    <div id="container">
    <img id="img"></div>
    
    <script>
    function displayImg() {
      let fileUpload = document.getElementById("fileUpload").value;
      //alert(fileUpload);
      let image = document.getElementById("img");
      img.src = fileUpload;
    
    }
    </script>
    
    </body>
    </html> 
    

    NOTE: The value property only returns the name of the file so the image should be located in the same folder as that of code.Or if you want to, you can add the path of the file before.