How to detect input type=file "change" for the same file?
To trigger a change event for the same file on <input type="file">
, empty the input's value after file selection:
This method resets the input, thereby letting you detect the same file repeatedly.
When you need the same file, again and again...
How to milk the same cow, more than once
Several methods exist to clear the input value, working consistently throughout frameworks and vanilla JavaScript:
.attr
vs .prop
, the jQuery conundrum
In jQuery, swapping .attr('value', '')
with .prop('value', '')
offers more foolproof results. The latter directly modifies the property and proves more reliable:
jsFiddle, your playground for curiosity
Fire up the online code editor jsFiddle and you can test these behaviors in real-time. Innovation is just one link away.
Fore-warnings and Fore-arming
Although the method is straightforward, remember:
- Test extensively on different browsers for a streak of consistency.
- Handle click events tied to the file input with caution.
- Alert! Browsers' security constraints may sometimes lead to varying behavior.
TypeScript wisdom
Ensuring type safety with TypeScript
When using TypeScript, you must incorporate type safety when clearing the input value:
Here, we ensure that event.target
is seen as an HTMLInputElement
, which lets us safely modify input.value
.
More edge cases, because life is edgy
The case of uncertain clicks
A user might click on the file input but cancel without selecting a file. In this case, it is critical to verify file selection:
The case of accidentally choosing your ex (file)
For applications that don't require processing the same file repeatedly, you might need additional logic to prevent accidental reselection:
Was this article helpful?