Explain Codes LogoExplain Codes Logo

Html input file selection event not firing upon selecting the same file

html
file-input
event-handling
form-upload
Nikita BarsukovbyNikita Barsukov·Aug 21, 2024
TLDR

To always trigger the change event when re-selecting the same file on <input type="file">, you need to clear the input value after each change.

document.getElementById('fileInput').addEventListener('change', function () { // Your file handling logic here // Clearing input for the next action this.value = ''; });

This works because setting this.value = '' reinitializes the input to receive the same file.

Understand the file input 'change' event

The change event of file input is triggered whenever a new file is selected. However, selecting the same file doesn't trigger the event because the browser doesn't detect a change.

Resetting the input value

The trick to circumvent this is to reset the input value after every file selection.

document.getElementById('fileInput').addEventListener('change', function (event) { const file = event.target.files[0]; // Your brilliant file processing code here // It's a kind of magic... Resetting input value to allow same file detection event.target.value = ''; });

The exceptional behavior of Firefox

Also note that FireFox might not recognize that value was reset and needs an explicit return false;.

document.getElementById('fileInput').addEventListener('click', function () { this.value = null; // FireFox likes to play hard to get. We are reassuring it here. return false; });

Working with multiple files

In case your fileInput supports multiple file selection (<input type="file" multiple>), remember that the change event provides a FileList object, not a single File.

document.getElementById('fileInput').addEventListener('change', function () { const files = Array.from(this.files); files.forEach(file => { // Handle each file individually like a boss }); // Reset the input for the next action this.value = ''; });

Advanced tips and tricks

Ensure enctype is set in forms

Ensure that your form has enctype='multipart/form-data' for proper handling of file uploads.

<form method="post" enctype="multipart/form-data"> <input type="file" id="fileInput" name="file"> </form>

Exploring the 'input' event for file uploads

While change event is useful in most scenarios, "input" event can provide a different level of control. It's worth exploring in real-time changes scenarios.

Take note of the following nuances

  • Specific to Chrome: Chrome might demand additional event handling if file selection dialog is dismissed without choosing a file.
  • When file selections are cancelled: If the user clicks cancel in the file dialog, change event won't trigger.
  • Browser's security measures: Browsers display a fake path (C:\fakepath) when handling file input for security, but the selected file's metadata is still accessible.