The Netlobo logo - a Nevada desert landscape

Clear File Input Using Javascript

A useful javascript function that allows you to clear the value of a file input field

Published May 19, 2009 by lobo235
Last updated on May 19, 2009

Changing the value of input fields using javascript is normally a very easy task. You will run into problems though if you are trying to change the value of a file input field because it is a read-only attribute. The reason it is read-only is so that you, the developer, can't change which file the user is uploading to your site. If you could change which file they are uploading you could, theoretically, have them upload a sensitive document or a file containing usernames and passwords. Of course you would need to be able to guess the name and location of the file on their computer but it's still a good security measure to keep it read-only.

So how are you supposed to clear the value of a file input then? I have created a function that will clear the file input value to make it easy to do. Here is the function:

function clearFileInput( id )
    var elem = document.getElementById( id );
    elem.parentNode.innerHTML = elem.parentNode.innerHTML;

Here is a short HTML page that shows how the function can be used:

<title>Clearing File Input Values</title>
<script type="text/javascript">
function clearFileInput( id )
var elem = document.getElementById( id );
elem.parentNode.innerHTML = elem.parentNode.innerHTML;
<form method="post" enctype="multipart/form-data">
<input type="file" name="myFile" id="fileInput1" />
<input type="submit" name="s" value="Upload" />
<a href="javascript:clearFileInput( 'fileInput1' );">Clear File Input Value</a>

 I hope this little function helps you as much as it has helped me. If you run into any problems when using the clearFileInput function you can try wrapping your file input boxes in a div or span to isolate the effects of the function. Otherwise, the function could have an effect on the other elements that have the same parent as your file input box. Feel free to use this code wherever you want, no license is required. Please leave a comment if this function helped you at all or if you decided to include it on your website.

15 comments for this article.

Other great Web Development and Programming articles on
Clean URLs using Apache's mod_rewrite
Preventing MySQL Injection attacks with PHP
Resizing an Image Using PHP and the GD2 Library