Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing file input box in Internet Explorer

I have an file upload box and a clear button on my page. When I press the clear button, I want the text in the file upload box to be cleared.

The following works in Firefox, but doesn't in IE (the text stays there). Is there a workaround for this?

$("#clear").click( function() {
    $("#attachment").val("");
    //document.myform.attachment.value = "";
})

HTML:

<form name="myform">
    <input type="file" name="attachment" id="attachment" />
</form>
<br /><button id="clear">Clear Attachment</button>

jsFiddle

like image 941
tskuzzy Avatar asked Aug 08 '11 19:08

tskuzzy


3 Answers

One solution I've found is simply doing:

document.getElementById('myUploadField').parentNode.innerHTML = document.getElementById('myUploadField').parentNode.innerHTML;

Seems like it shouldn't work, but it does.

like image 63
Maxx Avatar answered Sep 29 '22 14:09

Maxx


This solution is more elegant than cloning the input element. You wrap a <form> around the element, call reset on the form, then remove the form using unwrap(). Unlike the clone() solutions above, you end up with the same element at the end (including custom properties that were set on it).

Tested and working in Opera, Firefox, Safari, Chrome and IE6+. Also works on other types of form elements, with the exception of type="hidden".

http://jsfiddle.net/rPaZQ/

function reset(e) {
  e.wrap('<form>').closest('form').get(0).reset();
  e.unwrap();
}​
like image 42
slipheed Avatar answered Sep 29 '22 16:09

slipheed


It's readonly in IE8 onwards, so you can't clear it. The simplest way around this security feature is to replace the element with a copy.

Edit Found a previous answer to this that suggests the same approach! Clearing <input type='file' /> using jQuery

like image 28
andyb Avatar answered Sep 29 '22 15:09

andyb