5

Possible Duplicate:
Clearing <input type='file' /> using jQuery

This is my code:

 <input ID="fileUpload1" runat="server" type="file" style="width:275px; position:absolute; left:1px"/>

I've try some solutions:

$("input[type='file']").val('');
$('#DivfileUpload').replaceWith("<input class=VWButton ID=fileUpload1 runat=server type=file style=width:275px; position:absolute; left:1px/>");

and many others from the web but no succeed.

Community
  • 1
  • 1
anmarti
  • 5,045
  • 10
  • 55
  • 96

3 Answers3

9

You cannot set the value of a file input for (obvious) security reasons.

If you want to clear it, you need to reset the form it is in.


Replacing it with a new one should also work, but do it with valid code. (which means don't try to include server side code such the ASP runat=server attribute/value and do quote attribute values that aren't plain words (e.g. your style attribute)).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
7

Attempting to set the value with .val('') will fail in some browsers (like IE) for security reasons.

Your best options is to reset the form:

$('form').trigger('reset');

Or to use your replacement code, with slight modification (making sure the HTML valid):

$('#fileUpload1').replaceWith('<input id="fileUpload1" type="file" style="width:275px; position:absolute; left:1px"/>');

If you style the box with CSS, your code becomes even simpler.

The CSS:

#fileUpload1 {
    width: 275px;
    position: absolute;
    left: 1px;
}

The JavaScript:

$('#fileUpload1').replaceWith('<input id="fileUpload1" type="file"/>');

A more advanced option is to hide the file upload box when the page is loaded, then create a clone of it that gets shown to the user. When you need to clear it, you delete the clone, then re-clone the original hidden one. This method also allows you to make multiple copies of the input box if you want to allow the user to upload more than one file. I will leave the implementation details up to you. ;)

-2
$(function() { 
  $('#fileUpload1').val(''); 
});
hawx
  • 1,629
  • 5
  • 21
  • 37