3

//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!**
4
  • $('input_element').get(0).target.files.length try Commented Nov 23, 2016 at 20:02
  • You could just move the even function outside of the listener. So you'd have function check(){ /* ... */ } $('input_element').change(check); check(); Commented Nov 23, 2016 at 20:02
  • $('input_element').get(0).target.files.length is already there, it returns cant ready property length if undefine Commented Nov 23, 2016 at 20:06
  • 1
    It should be $('input_element').get(0).files.length without .target OR even shorter $('input_element')[0].files.length. Commented Nov 23, 2016 at 23:01

2 Answers 2

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

JS:

document.getElementById('fileInput').files.length > 0 // will be true if there's a file
Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.