VOOZH about

URL: https://www.geeksforgeeks.org/jquery/how-to-reset-input-type-file-using-javascript-jquery/

⇱ How to Reset an <input type="file"> in JavaScript or jQuery - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Reset an <input type="file"> in JavaScript or jQuery

Last Updated : 20 Sep, 2024

Sometimes, you may want to clear a file that has been selected by the user in an <input type="file"> field, without having to reload the entire page. This can be useful if the user wants to reselect a file or if you need to reset a form.

There are two main ways to reset a file input in JavaScript/jQuery:

1. Using jQuery’s wrap() Method

In this approach, we temporarily wrap the file input element inside a <form> element, then reset the form. By calling form.reset(), we can reset the file input, clearing any selected files.

Example: In this example, the wrap() method temporarily wraps the file input (#infileid) inside a form element. This allows the reset() method to clear the file input. Afterward, the unwrap() method removes the temporary form.

Output:

👁 How to reset input type = "file" using JavaScript/jQuery?
How to reset input type = "file" using JavaScript/jQuery?

Explanation:

  • The file input (<input type="file" id="infileid">) is temporarily wrapped in a form using $('#infileid').wrap('<form>').
  • We call form.reset() on the wrapped form to clear the file input.
  • After resetting, the file input is "unwrapped" from the temporary form using $('#infileid').unwrap().

2. Using file.value = ''

This is a simpler and more direct approach. You can reset the file input by setting its value property to an empty string, which removes any selected files.

Example: In this example, we use JavaScript to reset a file input. The resetFile() function targets the file input element with the class .file and clears its value, effectively resetting the file selection.

Output:

👁 How to reset input type = "file" using JavaScript/jQuery?
How to reset input type = "file" using JavaScript/jQuery?

Explanation:

  • The file input (<input type="file" class="file">) is selected using document.querySelector().
  • By setting the value property of the file input to an empty string (''), the file selection is cleared, and the input is reset.
Comment

Explore