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

Jquery

Jquery Problem Overview


> 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,

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBigJobbiesView Question on Stackoverflow
Solution 1 - JqueryClaytonView Answer on Stackoverflow
Solution 2 - JqueryJames KhouryView Answer on Stackoverflow