0

I need to clear a file upload input field when the page loads. I have looked at 10-15 various ways to do this via stackoverflow, however every suggestion includes a reset button where I want to clear it on page load so that it is reset/cleared if a user clicks the back button on their browser.

I am currently using this code to reset the entire form, it works well for all of the dropdowns however it does not clear the file input field

function init() {
    // Clear forms here
    //reset inputs
$('#upload_form').trigger("reset");
//reset upload form

}

window.onload = init;

From my researh this seems to have the most upvotes from the community Clearing <input type='file' /> using jQuery

Cheers!

2 Answers 2

5

You don't need jQuery for that:

function init() {
  document.getElementById("upload_form").reset();
}

window.onload = init;
Sign up to request clarification or add additional context in comments.

1 Comment

It does work on my computer, if the input is in a <form>: jsfiddle.net/BZjfL/2
2

One way to reset the file input type field is to replace it with a new one:

function reset() {
    var input = document.querySelector('.file-input');
    var newInput = input.cloneNode(true);
    input.parentNode.replaceChild(newInput, input);
}

Example

http://jsfiddle.net/d25nV/

2 Comments

There's no need to alter the DOM for that.
Not me: although it's unnecessarily complex, it's not wrong.

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.