How to clear an HTML file input using JavaScript
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
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.
1 | input.value = '' or input.value = null; |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <!DOCTYPE html> <html> <head> <title> How to clear an HTML file input using JavaScript - Clue Mediator </title> <script> function resetFile() { const file = document.querySelector('.file'); file.value = ''; } </script> </head> <body> <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> </body> </html> |
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.
1 2 3 4 5 6 | function resetFile() { const file = document.querySelector('.file'); var emptyFile = document.createElement('input'); emptyFile.type = 'file'; file.files = emptyFile.files; } |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!DOCTYPE html> <html> <head> <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> </head> <body> <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> </body> </html> |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂