How to clear an HTML file input using JavaScript
📅April 14, 2022
If you are using file input in the form, you may need to clear the input after submitting the form. So today we will show you how to clear an HTML file input using JavaScript.
Checkout more articles on JavaScript
- How to convert a string into a camel case in JavaScript
- How to highlight searched text using JavaScript
- How to create an auto-resize Textarea in JavaScript
- Detect a mobile device using JavaScript
Way to clear an HTML file input
1. Set the empty or null value
For the modern browser, we can set the empty or null value.
input.value = '' or input.value = null;
Example:
<title>
How to clear an HTML file input using JavaScript - Clue Mediator
</title>
<script>
function resetFile() {
const file = document.querySelector('.file');
file.value = '';
}
</script>
<h3>How to clear an HTML file input using JavaScript - <a href="https://www.cluemediator.com" target="_blank" rel="noreferrer noopener">Clue Mediator</a></h3>
<input type="file" class="file">
<button onclick="resetFile()">Reset file</button>
2. Replace a new input file element value with the old element value
In this second method, we will create a new file input element and replace the value of the new element with the old element value.
function resetFile() {
const file = document.querySelector('.file');
var emptyFile = document.createElement('input');
emptyFile.type = 'file';
file.files = emptyFile.files;
}
Example:
<title>
How to clear an HTML file input using JavaScript - Clue Mediator
</title>
<script>
function resetFile() {
const file = document.querySelector('.file');
var emptyFile = document.createElement('input');
emptyFile.type = 'file';
file.files = emptyFile.files;
}
</script>
<h3>How to clear an HTML file input using JavaScript - <a href="https://www.cluemediator.com" target="_blank" rel="noreferrer noopener">Clue Mediator</a></h3>
<input type="file" class="file">
<button onclick="resetFile()">Reset file</button>
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂