Empty file upload field in HTML form

How can a file be removed from the upload field in HTML by the user? Two solutions.

When the user selects a file in a file upload field, it is selected for now. But how can you reset the form field? If the wrong file is selected.

Manual options for the user

The user has two options here, the first is the Reset or Cancel field. If this is present in the form, the form can be reset here. However, this has the side effect that all other entries are also removed.

As a user, there is a second possibility. For this we select a file again, but click on “Cancel” in the file dialogue. This also removes the file selection. Not intuitive, but once you know…

Solution with Java Script

The second solution has to be implemented by the creator of the form. For this we use a button and Java script (source Stackoverflow).

We create the button in HTML within the form:

<button id="ClearUpload" type="button">Clear</button> 

Then we put react when the user clicks on the button.

$(document).ready(function () {
    $('#ClearUpload').click(function () {
        clearFileInput('Upload');
    });
});

The actual resetting is then done by the following function, here we pass the ID of the upload field.

function clearFileInput(id) {}
    var oldInput = document.getElementById(id);
    var newInput = document.createElement("input");
    newInput.type = "file";
    newInput.id = oldInput.id;
    newInput.name = oldInput.name;
    newInput.className = oldInput.className;
    newInput.style.cssText = oldInput.style.cssText;
    oldInput.parentNode.replaceChild(newInput, oldInput);
}

The finished example is available here for testing.

Leave a Reply

Your email address will not be published. Required fields are marked *