How to check if a file is selected using javascript?

In php so you can check if a file is selected:

$_FILES['item']['size']>0 

what about javascript?

I need to know, because I have a function that will only work if a file is selected.

+6
javascript file php
source share
3 answers

http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-49531485 says:

value of type DOMString
When the element's type attribute is set to text, file , or password, it represents the current content of the corresponding form control in the interactive user agent.
 <html> <head><title>...</title> <script type="text/javascript"> function foo() { var f = document.getElementById("f1"); alert( ""==f.value ? "nothing selected" : "file selected"); } </script> </head> <body> <form> <div> <input id ="f1" type="file" name="x" /> </div> </form> <button onclick="foo()">click</button> </body> </html> 
+19
source share

I am using this javascript:

 var file_selected = false; function showNoFile() { if(!file_selected) { alert('No file selected!'); } // or anything else } 

with this html for the file button:

 <input type='file' onchange="file_selected = true;" ...> .... <input type='submit' onclick='showNoFile();'> 

hope this helps!

+6
source share

So, let's say you have some kind of html form, and you have user input to upload files:

 <label for="imageUploadButton"> <span class="btn" style="padding-left: 10px;">Click here for uploading a new picture</span> </label> <input type="file" name="avatar_picture" accept="image/gif,image/jpeg,image/png" id="imageUploadButton" style="visibility: hidden; position: absolute;"> 

And you want to check the name of the file that the user has selected / selected:

Using jquery

 <script type="text/javascript"> $(function() { $("input:file").change(function (){ var fileName = $(this).val(); alert(fileName); //Do with the filename whatever you want }); }); </script> 

@ fooobar.com/questions/38646 / ...

For those using requireJS:

 $("input:file").change(function () { var fileName = $(this).val(); alert(fileName); //Do with the filename whatever you want }); 
0
source share

All Articles