Clearing file input box in Internet Explorer

2019-01-18 11:05发布

问题:

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

回答1:

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



回答2:

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.



回答3:

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


回答4:

This worked for me:

 $("input[type='file']").replaceWith($("input[type='file']").clone(true));



回答5:

use simple javascript:

formname.reset();

See the Demo: http://jsfiddle.net/rathoreahsan/YEeGR/



回答6:

Try to use the below method to clear the input file.

Include this script:

 <script>
 function clearFileInputField(tagId) {
 document.getElementById(tagId).innerHTML =
    document.getElementById(tagId).innerHTML;
}
</script>

Change HTML to this:

<div id="uploadFile_div">
<input type="file" class="fieldMoz" id="uploadFile" onkeydown="return false;" size="40" name="uploadFile"/>
</div>
<a onclick="clearFileInputField('uploadFile_div')" href="javascript:noAction();">Clear</a>`


回答7:

Use the old-fashioned <input type="reset" value="clear this">