开发者

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


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.


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


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


This worked for me:

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


use simple javascript:

formname.reset();

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


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>`


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜