views:

5429

answers:

4

Hi,

Is it possible to clear an <input type='file' /> control value with jQuery? I've tried the following:

$('#control).attr({ value: '' });

But its not working.

Need help. TIA.

+10  A: 

Quick answer: replace it.

$("#clear").click(function(event){
  event.preventDefault();
  $("#control").replaceWith("<input type='file' id='control' />");
});

<input type="file" id="control" />
<a href="#" id="clear">Clear</a>


Possibly of interest: "How do I serialize form type input with jQuery"

Jonathan Sampson
I have tried it. Its not working
That's because the example is not for a file control, it's for a text control.
mgroves
Answer updated. Sorry, I was confused by the question at first.
Jonathan Sampson
Wow, very novel answer!
mgroves
Thanks, mgroves.
Jonathan Sampson
Nice thinking :) Gotta love the fun work around :)
Boushley
Yeah. Seems like one of those types of issues I'd spend 20 minutes trying to work out before thinking about a full replacement :)
Jonathan Sampson
Good approach :)
El Yobo
+1  A: 

The value of file inputs is read only (for security reasons). You can't blank it programatically (other than by calling the reset() method of the form, which has a broader scope than just that field).

David Dorward
I'm confused - I tried $("#inputControl").val("") and it did indeed blank the field. Am I missing something?
Jonathan Sampson
A: 

adapted from Jonathan Sampson

$("#clear").click(function(event){
 event.preventDefault();
 $("#control").attr({ value: '' });;
});
vee
Works for most everything except IE ;)
Typeoneerror
+1  A: 

In IE8 they made the File Upload field read-only for security. See the IE team blog post:

Historically, the HTML File Upload Control () has been the source of a significant number of information disclosure vulnerabilities. To resolve these issues, two changes were made to the behavior of the control.

To block attacks that rely on “stealing” keystrokes to surreptitiously trick the user into typing a local file path into the control, the File Path edit box is now read-only. The user must explicitly select a file for upload using the File Browse dialog.

Additionally, the “Include local directory path when uploading files” URLAction has been set to "Disable" for the Internet Zone. This change prevents leakage of potentially sensitive local file-system information to the Internet. For instance, rather than submitting the full path C:\users\ericlaw\documents\secret\image.png, Internet Explorer 8 will now submit only the filename image.png.

Jon Galloway