149

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?

2

14 Answers 14

228

This should work:

$imageClear.on('click', function() { 
    $imageFile.val(''); 
});
Sign up to request clarification or add additional context in comments.

5 Comments

Yes, it is a relatively simple jQuery code. It is a cross-browser solution.
Guys, <input type=file /> is readonly after selecting the file in >= IE8, for security reasons, here is the similar Q and correspondent A for the solution proposed here.
<input type=file /> data type is file, we can't clear it by pass empty string to input field.
Working on Chrome too. That is may useful to see this stackoverflow.com/a/11953476/1830909 and my comment below that.
How can i remove file in multiple file upload in file input using jquery?
83

Clear file input with jQuery

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

Clear file input with JavaScript

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

2 Comments

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.
I agree completely. Lots of framework's functions fail on file type input elements and they change over time. This pure JavaScript answer is PERFECT.
11

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()

Comments

7

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/

Comments

7

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

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

3 Comments

simple and great solution to clear the file input
@MohamedRaza Thanks hope my answer was helpful.
yes, it was helped me
6

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

Comments

3

this code works for all browsers and all inputs.

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

1 Comment

I recommend you use like : $(document).ready(function( {$('#your_target_input').attr('value', ''); } );
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']"));

1 Comment

'Thank you bro, It help me, but when updating data nothing shows, can I share the code?
1

This works to

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

Comments

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>

Comments

1
$('#myImage').filestyle('clear');

I'm using

  • jquery 2.2.1 &
  • jquery UI 1.11.4

1 Comment

This method doesn't seems to exist for me
0

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

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

Comments

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.

Comments

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));
        }
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.