How to Reset File Input with jQuery
Resetting a file input is possible and pretty easy with jQuery and HTML. For that purpose, you should wrap a <form> around <input type="file">, then call reset on the form by using the reset() method, then remove the form from the DOM by using the unwrap() method.
The following jQuery code piece is supported by major browsers and also works on other types of form elements except type="hidden":
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
</head>
<body>
<form>
<div>
<label>File</label>
<br>
<input id="fileId" type="file">
</div>
<div>
<label>Name</label>
<br>
<input id="textId" type="text" value="File name">
</div>
<div>
<button id="btn-file-reset-id" type="button">Reset file</button>
<button id="btn-text-reset-id" type="button">Reset text</button>
</div>
</form>
<script>
$(document).ready(function() {
$('#btn-file-reset-id').on('click', function() {
$('#fileId').val('');
});
});
$(document).ready(function() {
$('#btn-text-reset-id').on('click', function() {
$('#textId').val('');
});
});
</script>
</body>
</html>
If you have the buttons to trigger the reset of the field inside of the <form> element, you must call the .preventDefault() method on the event to prevent the <button> from triggering a submit.
The reset() method
HTMLFormElement.reset() is a built-in method that is used to reset all form elements to their initial values. It is a simple and efficient way to clear out form data and start over. When the method is called, it resets all input fields, checkboxes, and radio buttons to their default values.
Using HTMLFormElement.reset() is quite simple. All you need to do is call the method on the form element. Here is an example:
const form = document.querySelector('form');
form.reset();