Home » Php » php – how to check if a file is selected using javascript?

php – how to check if a file is selected using javascript?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&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>

Answer:

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!

Answer:

So lets say you have some html form and you have a custom file upload input:

<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 filename of the file the user has chosen/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>

@https://stackoverflow.com/a/5670938/2979938

For those using requireJS:

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