[jquery] How to clear File Input

Below is part of the jquery code I have which displays the file input and a "Clear File" button.

var $imagefile = $('<input />').attr({
    type: 'file',
    name: 'imageFile',
    class: 'imageFile'
});

$image.append($imagefile);

var $imageclear = $('<input />').attr({
    type: 'button',
    name: 'imageClear',
    class: 'imageClear',
    value: 'Clear File'
});

$image.append($imageclear);

Now the reason I have the "Clear File" button is because if you click on the button, then it will clear anything that is in the file input. How do I code it so that it actually clears the file input when I click on the "Clear File" button?

This question is related to jquery

The answer is


In my case other solutions did not work than this way:

$('.bootstrap-filestyle :input').val('');

However, if you will have more than 1 file input on page, it will reset the text on all of them.


Clear file input with jQuery

$("#fileInputId").val(null);

Clear file input with JavaScript

document.getElementById("fileInputId").value = null;

Another solution if you want to be certain that this is cross-browser capable is to remove() the tag and then append() or prepend() or in some other way re-add a new instance of the input tag with the same attributes.

<form method="POST" enctype="multipart/form-data">
<label for="fileinput">
 <input type="file" name="fileinput" id="fileinput" />
</label>
</form>

$("#fileinput").remove();
$("<input>")
  .attr({
    type: 'file',
    id: 'fileinput',
    name: 'fileinput'
    })
  .appendTo($("label[for='fileinput']"));

I have done something like this and it's working for me

$('#fileInput').val(null); 

This works to

 $("#yourINPUTfile").val("");

By Setting $("ID").val(null), worked for me


This is the method I like to use as well but I believe you need to add the bool true parameter to the clone method in order for any events to remain attached with the new object and you need to clear the contents.

    var input = $("#fileInput");

    function clearInput() {
        input = input.val('').clone(true);
    };

https://api.jquery.com/clone/


for React users

e.target.value = ""

But if the file input element is triggered by a different element (with a htmlFor attribute) - that will mean u don't have the event

So you could use a ref:

at beginning of func:

const inputRef = React.useRef();

on input element

<input type="file" ref={inputRef} />

and then on an onClick function (for example) u may write

inputRef.current.value = "" 
  • in React Classes - same idea, but difference in constructor: this.inputRef = React.createRef()

get input id and put val is empty like below: Note : Dont put space between val empty double quotes val(" ").

 $('#imageFileId').val("")

this code works for all browsers and all inputs.

$('#your_target_input').attr('value', '');