Skip to content
Advertisement

HTML + JS: Clear File Input on button click

I want to tell my backend, I deleted the assigned file it already loaded:

<input id="pic" name="pic" type="file" onclick="this.value=null;" onchange="uploadFile(this);">
<button id="pic-delete" type="button" onclick="removeFile(this);"><i someicon></i></button>

where the onclick function looks like:

removeFile = function() {
    var ipt = document.getElementById("pic");
    ipt.value = null; // <--- problem here
    console.log("worked...")
}

my problem now is: I can differentiate the request in the browser Network tab whether I do nothing or hit the delete button. Both times the input field does not show up. I wanted to add ipt.value="DELETE" so I can catch that in the backend, but this leads to an error:

Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable

From what I can tell the error always occurs if I put anything else but ipt.value = null or ipt.value = "" in this line.

A fiddle with the full code to show the error: https://jsfiddle.net/rvc8sbjy/3/

Advertisement

Answer

There are a few errors. The way you were trying to extract the ID is wrong. A much easier approach is to just use .replace

      var inputFieldID = v.id.replace("-delete", "");

Second – you can’t set the value to an non-empty string. To reset it just set it to an empty one:

          ipt.value = "";

Working example:

https://jsfiddle.net/5yqohjzv/

Advertisement