2

This is what I have in HTML:

<img src="images/defaultProfile.jpg" id="image">
<input type="file" name="pic" accept="image/*" id="imgPath">
<input type="submit" onclick="uploadImg()">

The image with an id of "image" automatically loads a default image from a designated directory by default. Then, the user can I pick an image from the file picker. When the user hits the submit button written on the last line, The uploadImg() written on javaScript file will get the image from input and change the image displayed.

But, my question is how I can enable the user to change the image by just picking a image file from the directory without hitting the "submit" button.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320

2 Answers2

2

You can add a change listener to the image input:

document.querySelector('#imgPath').onchange = () => {
  console.log('Now uploading...');
  // uploadImg();
};
<input type="file" name="pic" accept="image/*" id="imgPath">
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Take a look at this Why can't I do <img src="C:/localfile.jpg">?. If your plan is to display an image before uploading to the server, that is not going to work. What you can do is write an "onchange" event (https://www.w3schools.com/jsref/event_onchange.asp) to your file selection input line (2nd line in your code), and upload it to a temporary directory and display it. As the user clicks on the upload button, you can make the change permanent. If the user cancels, you will display the default profile page.

Raj006
  • 562
  • 4
  • 18