jQuery - Detecting if a file has been selected in the file input [duplicate]

Possible Duplicate:
jQuery: get the file name selected from <input type=“file” />

I have a standard file input box

<input type="file" name="imafile">

I also have a bit of text down the page like so

<span class="filename">Nothing selected</span>

I was wondering if it is possible to have the text update with the name of the file selected in the file input box?

Cheers,


You should be able to attach an event handler to the onchange event of the input and have that call a function to set the text in your span.

<script type="text/javascript">
  $(function() {
     $("input:file").change(function (){
       var fileName = $(this).val();
       $(".filename").html(fileName);
     });
  });
</script>

You may want to add IDs to your input and span so you can select based on those to be specific to the elements you are concerned with and not other file inputs or spans in the DOM.


I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has

.bind("change", function(){ ... });

Or

.change(function(){ ... }); 

which are equivalents.

http://api.jquery.com/change/

for a unique selector change your name attribute to id and then jQuery("#imafile") or a general jQuery('input[type="file"]') for all the file inputs