How to clear the HTML file input using JavaScript
In this tutorial, we are going to learn about how to clear the HTML file input (value) in JavaScript with the help of an example.
Consider, that we are having a following file ‘input’ field like this in our HTML:
<input type="file" id="profile" />
To clear the HTML file input value in JavaScript, first we need to access that element inside the JavaScript using the document.getElementById()
method then set it’s value to a “null”.
Here is an example:
const fileInput = document.getElementById("profile");
// cleared the file input value
fileInput.value = null;
Clearing the file input by button click
We can also clear an file input in JavaScript, whenever a user is clicked the button.
Here is an example:
HTML:
<input type="file" id="profile" />
<button id="clearBtn">Clear</button>
JavaScript:
const fileInput = document.getElementById("profile");
const btn = document.getElementById("clearBtn");
btn.addEventListener("click", ()=>{
// cleared the file input value
fileInput.value = null;
})
In the above example, we first added a button html element then accessed it inside the JavaScript using the document.getElementById() method, then added a click event listener to it. So, whenever a button is clicked it clears the file input value.