开发者

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

开发者 https://www.devze.com 2023-02-25 11:19 出处:网络
This question already has answers here: 开发者_C百科 Closed 10 years ago. Possible Duplicate: jQuery: get the file name selected from <input type=“file” />
This question already has answers here: 开发者_C百科 Closed 10 years ago.

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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消