Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a file is selected using javascript?

In php this is how you would check if a file is selected:

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

what about in JavaScript?

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

like image 270
noob Avatar asked Sep 13 '09 10:09

noob


People also ask

How do you check if a file is uploaded or not in JS?

length property to check file is selected or not. If element. files. length property returns 0 then the file is not selected otherwise file is selected.

How do you check if a file is an image Javascript?

You can check if the file is an image using the filename in javascript. This function helps you get the file extension and return true or false if the file extension does not exist in the provided file extensions array.

How check file is selected or not in PHP?

To check whether any file is existing or not then we can use the below-mentioned PHP function. To find the existence of the files, we use file_exists() function. This function is used to check whether a file or directory exists or not.

How check file is empty in laravel?

It is very easy to check if uploaded file or image empty or not if you are using core PHP. But as we know laravel 5 provide us object of file, So we can not determine using empty(). However, we can simply do it using hasFile() and isValid() of laravel predefine.


2 Answers

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

value of type DOMString
When the type attribute of the element has the value "text", "file" or "password", this represents the current contents of the corresponding form control, in an 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>
like image 89
VolkerK Avatar answered Oct 18 '22 20:10

VolkerK


I use 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 that helps!

like image 34
Tanner Ottinger Avatar answered Oct 18 '22 19:10

Tanner Ottinger