139

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?

yceruto
  • 9,230
  • 5
  • 38
  • 65
user1181690
  • 1,443
  • 2
  • 11
  • 12

14 Answers14

213

This should work:

$imageClear.on('click', function() { 
    $imageFile.val(''); 
});
yceruto
  • 9,230
  • 5
  • 38
  • 65
Guillaume Poussel
  • 9,572
  • 2
  • 33
  • 42
  • 1
    Yes, it is a *relatively simple* jQuery code. It is a cross-browser solution. – Guillaume Poussel Mar 08 '12 at 12:45
  • 4
    Guys, `` is `readonly` after selecting the file in >= **IE8**, for security reasons, here is the similar [Q](http://stackoverflow.com/q/1043957/1548719) and correspondent [A](http://stackoverflow.com/a/1188853/1548719) for the solution proposed here. – Paul T. Rawkeen Aug 01 '12 at 07:36
  • 1
    `` data type is file, we can't clear it by pass empty string to input field. – Usman Mughal Oct 16 '17 at 11:24
  • Working on Chrome too. That is may useful to see this https://stackoverflow.com/a/11953476/1830909 and my comment below that. – QMaster Oct 07 '18 at 17:08
  • 1
    How can i remove file in multiple file upload in file input using jquery? – always-a-learner Mar 12 '20 at 09:25
78

Clear file input with jQuery

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

Clear file input with JavaScript

document.getElementById("fileInputId").value = null;
Arvin Jayanake
  • 1,475
  • 3
  • 14
  • 26
  • This is only method that truly works across all input types. Using .val('') on file inputs prevents normal submission if the file has been changed since initial render. .val(null) clears the input back to it's initial state. – myshadowself Mar 09 '23 at 09:10
9

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()
Shani Kehati
  • 427
  • 5
  • 10
6

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/

meditari
  • 131
  • 2
  • 7
6

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

Syscall
  • 19,327
  • 10
  • 37
  • 52
6

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

 $('#imageFileId').val("")
Nagnath Mungade
  • 921
  • 10
  • 11
3

this code works for all browsers and all inputs.

$('#your_target_input').attr('value', '');
reza laki
  • 81
  • 1
  • 8
  • I recommend you use like : `$(document).ready(function( {$('#your_target_input').attr('value', ''); } );` – reza laki May 15 '20 at 03:01
2

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']"));
Iceman
  • 21
  • 1
1

This works to

 $("#yourINPUTfile").val("");
1
$('#myImage').filestyle('clear');

I'm using

  • jquery 2.2.1 &
  • jquery UI 1.11.4
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Catalyst
  • 465
  • 6
  • 14
1

This can solve your problem, i has problem when i pass the archive with accent into name and i solved verifying the size of archive and clear input if has something different than normal.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="file" placeholder="hello world" id="input_file" />

    <script
      src="https://code.jquery.com/jquery-3.6.1.js"
      integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
      crossorigin="anonymous"
    ></script>
    <script>
      $("input:file").change(function () {
        var fileInput = $(this); // => Gets the file data
        var fileSize = fileInput.get(0).files[0].size; // => Value in bytes
        if (fileSize == 0) {
          $("#input_file").val("");
          console.log('Something wrong :/');
        } else {
            console.log('good thats working :D');
        }
      });
    </script>
  </body>
</html>
0

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

$('#fileInput').val(null); 
Nikunj K.
  • 8,779
  • 4
  • 43
  • 53
0

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.

Piotr Sagalara
  • 2,247
  • 3
  • 22
  • 25
0

Okay, That's worked and approved;

$('.file-input-element').change();

$(document).on("change", 'input[type="file"][data-module-name="Test"]', function (e) {
    e.preventDefault();
    var controlName = $(this).attr('name');
    var fileFormData = new FormData();
    var files = e.target.files;
    if (files.length > 0) {
        var file = files[0];
        var fileName = file.name;
        var fileSize = file.size; //in bytes
        var fileType = file.type; //like "image/png"
        if (fileSize > App.maxAllowedSizeInBytes) {
            e.target.value = '';
            $(this).attr("value", '');
            $(this).change();
            toastr.error(langData.UIMaxFileSizeShouldBeFiveMb);
            return;
        } else {
            App.test.validation.ValidateFile(file);
            fileFormData.append("file", file, fileName);
            App.test.uploadFile(fileFormData, controlName, $(this));
        }
    }
});
Hotkey
  • 103
  • 7