Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery / Javascript check if input file is got files or not

//This is not a a duplicate question but what i need to do is check that a file input element has got files or not from anywhere in my javascript code without depending on built in events

//forexample...

$('input_element').change(function(event){
                    //code...
                    //any code here but
                    if(event.target.files.length>0){
                        //files around/selected
                    }else{
                        //code..
                        //files not around/selected
                    }
                })


                //But i need to check if files selected without that event ( anonymously... )
                //like

                if($('input_element').get(0).files.length>0){
                    //code
                    //here i get an error "can not read propert length of undefined!"
                    console.log('files are selected!')
                }else{
                    //code ...
                    //do something...
                }

            **//any help appreciated!**
like image 969
apexpals.com Avatar asked May 13 '26 22:05

apexpals.com


2 Answers

<input id="fileInput" type="file">

JS:

document.getElementById('fileInput').files.length > 0 // will be true if there's a file
like image 163
Bwaxxlo Avatar answered May 15 '26 13:05

Bwaxxlo


If you start off with a jQuery object e.g. var $input = $(selector), you need to use its native HTML element using $input[0] to access its properties which contains a files array.

Below is a quick example:

$(function() {
  var $input = $('[name=file]');
  $('button').click(function() {
    alert($input[0].files.length ? 'files were selected' : 'no files were selected');
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="file" multiple><br><br>
<button>Check</button>
like image 32
Mikey Avatar answered May 15 '26 11:05

Mikey