Categories
JavaScript Answers

How to Clear an HTML File Input with JavaScript?

Spread the love

Sometimes, we want to let users clear an HTML file input with JavaScript.

In this article, we’ll look at how to clear an HTML file input with JavaScript.

Setting the value Property of the File Input to an Empty String

We can set the value property of the file input to an empty string.

For instance, if we have the following HTML code:

<input type='file'>  
<button>  
  clear  
</button>

Then we can write:

const input = document.querySelector('input')  
const button = document.querySelector('button')  
button.addEventListener('click', () => {  
  input.value = '';  
})

to clear the file input when we click on the clear button.

We get the input and the button with document.querySelector .

Then we call addEventListener on the button with the 'click' string as the first argument to listen for clicks on the button.

In the event handler, we just set input.value to an empty string.

Then when we select a file for the input and click clear, we see that the selected file is gone.

We can also set value to null to do the same thing.

Conclusion

We can clear the file input with JavaScript by setting the value property of the file input to an empty string or null .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *