How to reset input type = “file” using JavaScript/jQuery?
In this article, we will learn how to rest input type=”file” using Javascript/Jquery. We can easily reset a file using jQuery and HTML. This can also be done using JavaScript and HTML.
These are the following ways:
Table of Content
- Using the wrap method in jQuery
- Using file.value = ”
- Using wrap method in jquery
Approach 1: Using the wrap method in jQuery
The best way to reset input type=file is by resetting the whole form. Wrap <input type = “file”> into <form> tags and reset the form:
Example: In this example, we will see the use wrap method.
HTML
<!DOCTYPE html> < html > < head > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > </ script > <!-- jQuery code to show the working of this method --> < script > $(document).ready(function () { $('#resetbtn').on('click', function (e) { let $el = $('#infileid'); $el.wrap('< form >').closest( 'form').get(0).reset(); $el.unwrap(); }); }); </ script > </ head > < body > < h2 style = "color:green" >w3wiki</ h2 > < form id = "find" name = "formname" > < p > < label >File</ label > < input id = "infileid" type = "file" > </ p > < p > < button id = "resetbtn" type = "button" > Reset file </ button > </ p > </ form > </ body > </ html > |
Output:
Approach 2: Using file.value = ”
The simplest way to reset the input is to change the filled value with nothing. This method works in every browser.
Example: In this example, we will see the use file.value = ‘ ‘
HTML
<!DOCTYPE html> < html > < head > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > </ script > <!-- jQuery code to show the working of this method --> < script > function resetFile() { const file = document.querySelector('.file'); file.value = ''; } </ script > </ head > < body > < h2 style = "color:green" > w3wiki </ h2 > < input type = "file" class = "file" /> < br > < button onclick = "resetFile()" > Reset file </ button > </ body > </ html > |
Output:
Approach 3: Using wrap method in jquery
Wrap <input type = “file”> in to <form> tags and reset the form.
Example: In this example, we will see the use of wrap method in jquery.
HTML
<!DOCTYPE html> < html > < body > < h2 style = "color:green" > w3wiki </ h2 > < form id = "find" name = "formname" > < p > < label >File</ label > < input type = "file" > </ p > < p > < button id = "resetbtn" type = "button" onClick = "this.form.reset()" > Reset file </ button > </ p > </ form > </ body > </ html > |
Output: