0

So I want to set <img src=""> attribute using JavaScript, but the source would be a input element value.

<img src="" id="userImage" onclick="changeImage()">
<input type="file" id="imageInput">
function changeImage() {
   var userImage = document.getElementById("imageInput").value;
   document.getElementById("userImage").src = userImage;
}

Note: <input type="image"> don't work for me as it doesn't show window to select image.
When I open console, it shows

Failed to load resource:
net::ERR_UNKNOWN_URL_SCHEME

1 Answers1

1

You can use FileReader to read the input as a dataURL and then append that url as the image src

function read(val) {
  const reader = new FileReader();

  reader.onload = (event) => {
    document.getElementById("divOutput").src = event.target.result;
  }

  reader.readAsDataURL(val.files[0]);
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File uploader</title>
    <script src="./script.js" defer></script>
</head>

<body>
    <h1>My file uploader</h1>

    <input type='file' id='userImage' onchange = "read(this)">
    <img id='divOutput'></div>


</body>

</html>
AnanthDev
  • 1,605
  • 1
  • 4
  • 14
  • Please don't answer questions that already have an answer on Stack Overflow. Flag to mark them as a duplicate instead. See [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) and [Why are some questions marked as duplicate?](https://stackoverflow.com/help/duplicates) – Ivar Oct 16 '21 at 11:30
  • Yikes i understand but how was i supposed to know :/ – AnanthDev Oct 16 '21 at 11:32
  • Well, 12 minutes before you submitted your answer there was already a link posted under the question that links to a duplicate. But even if there wasn't, you should realize that there are over 2 million JavaScript questions on Stack Overflow. Odds of noone ever asking to put a file input into a `` are _very_ slim. A swift Google search should yield some results. – Ivar Oct 16 '21 at 11:34
  • 1
    @Ivar yea its my bad, i was writing the code on snippet, i didnt see your comment till now, ill make sure to not do this in the future – AnanthDev Oct 16 '21 at 11:35