views:

1005

answers:

4

i want to reset a file upload field when the user selects another option

is this possible via JS? i'm suspecting that the file upload element is treated differently b/c it interacts with the user's FS, and maybe it's immutable

basically, what i want is something like (pseudo)

// choose selecting existing file
$('#select-file').bind('focus', function() {
  // clear any files currently selected in #upload-file
  $('#upload-file').val(''); 
}) ;

// choose uploading new one - this works ok
$('#upload-file').bind('focus', function() {
  // clear any files currently selected in #select-file
  $('#select-file').val(''); 
}) ;
+4  A: 

Yes, the upload element is protected from direct manipulation in different browsers. However, you could erase the element from the DOM tree and then insert a new one in its place via JavaScript. That would give you the same result.

Something along the lines of:

$('#container-element').html('<input id="upload-file" type="file"/>');
Udo
very nice - will give this a shot, should be v little hassle to run off a copy of the existing element
Chris Burgess
+2  A: 

They don't get focus events, so you'll have to use a trick like this: only way to clear it is to clear the entire form

<script type="text/javascript">
    $(function() {
        $("#wrapper").bind("mouseover", function() {
            $("form").get(0).reset();
        });
    });
</script>

<form>
<div id="wrapper">
    <input type=file value="" />
</div>
</form>
Chad Grant
thanks - yes i had also wondered if there's even a UI method for the user to clear their own file upload field without resetting the entire form
Chris Burgess
+1  A: 

You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two. Here's an article that covers this with sample code: How to clear HTML file inputs

Chris Hynes
I tried the other two suggested options above, and the sample code at this link was the one which worked best in the end. I really expected Udo's answer to do it, but it wasn't the go.I also tried http://gusiev.com/2009/04/clear-upload-file-input-field/Thanks Chris H
Chris Burgess
+2  A: 

The code I ended up using was,

clearReviewFileSel: function() {
  var oldInput = document.getElementById('edit-file-upload-review-pdf') ;
  var newInput = document.createElement('input');
  newInput.id    = oldInput.id ;
  newInput.type  = oldInput.type ;
  newInput.name  = oldInput.name ;
  newInput.size  = oldInput.size ;
  newInput.class  = oldInput.class ;
  oldInput.parentNode.replaceChild(newInput, oldInput); 
}

Thanks everyone for the suggestions and pointers!

Chris Burgess
Thank you for posting the code! You saved me time and frustration tonight.
NXT
In IE8, "class" is not a valid attribute. It's "className".
NXT