Categories
JavaScript Answers

How to fix HTML input file selection event not firing upon selecting the same file with JavaScript?

Spread the love

To fix HTML input file selection event not firing upon selecting the same file with JavaScript, we set the value of the file input to null when we click on the file input button.

For instance, we write

<input type="file" />

to add a file input.

Then we write

const [input] = document.getElementsByTagName("input");

input.onclick = (e) => {
  e.target.value = null;
};

input.onchange = (e) => {
  console.log(e.target.value);
};

to select the input with getElementsByTagName.

Then we set its onclick property to a function that clears the file input on click by setting e.target.value to null.

And we set its onchange property to a function that logs the selected file by logging e.target.value when any file is selected.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *