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.

2
  • Possible duplicate: stackoverflow.com/q/1043957/663604 Commented Aug 8, 2012 at 14:31
  • I use that answer but indeed no succced. Commented Aug 8, 2012 at 14:42

3 Answers 3

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)).

Sign up to request clarification or add additional context in comments.

3 Comments

so if I wrap the input type=file with a div and use the second option should work?
Can you list/explain security reasons?
@Satish — People keep private information in files on their computer. If any website you visited could read those files, it wouldn't be very private.
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. ;)

Comments

-2
$(function() { 
  $('#fileUpload1').val(''); 
});

1 Comment

$(ID).val(''); this gonna work if it is applied within any element's valid event

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.