Alex Rivera | Logout

Clearing <input type='file' /> using jQuery

Asked 2009-06-25T13:32:15.460
560

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

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

But it's not working.

Edit
Report

2 Answers

435

Quick answer: replace it.

In the code below I use the replaceWith jQuery method to replace the control with a clone of itself. In the event you have any handlers bound to events on this control, we'll want to preserve those as well. To do this we pass in true as the first parameter of the clone method.

<input type="file" id="control"/>
<button id="clear">Clear</button>
var control = $("#control");

$("#clear").on("click", function () {
    control.replaceWith( control = control.clone( true ) );
});

Fiddle: http://jsfiddle.net/jonathansampson/dAQVM/

If cloning, while preserving event handlers, presents any issues you could consider using event delegation to handle clicks on this control from a parent element:

$("form").on("focus", "#control", doStuff);

This prevents the need for any handlers to be cloned along with the element when the control is being refreshed.

answered 2009-06-25T13:33:43.960
-5

What? In your validation function, just put

document.onlyform.upload.value="";

Assuming upload is the name:

<input type="file" name="upload" id="csv_doc"/>

I'm using JSP, not sure if that makes a difference...

Works for me, and I think it's way easier.

answered 2011-06-22T14:43:33.933

Your Answer