2

this is html code :

<form method="POST" action="http://my-site.com/send-file" accept-charset="UTF-8" enctype="multipart/form-data">
      <input name="_token" type="hidden" value="6Yav0H6Cyp62Rhr6uAAEefzL7Yq0BqIHfhuYwzy4"> 
      <label for="file">File</label>
      <input id="iefile" name="img" type="file">
      <input type="submit" value="send">
</form>

this is js code :

 $('form').submit(function(e) { // capture submit
        e.preventDefault();
        size=$(this).find("input:file").files[0].size ;
        alert(size);
}

but in console this error displayed :

Uncaught TypeError: Cannot read property '0' of undefined

1 Answer 1

3

To retrieve properties of DOM elements you should use .prop():

$(this).find("input:file").prop('files')[0].size

This is because $(this).find() returns a jQuery object and not the DOM element directly. Alternatively, you can treat the results as an array and use the first element like so:

$(this).find("input:file")[0].files[0].size

As mentioned in the comments, you should also make sure a file was selected first:

var f = $(this).find("input:file")[0].files[0];
if (f) {
    // do something with f.size
}
Sign up to request clarification or add additional context in comments.

1 Comment

And hopefully they picked a file before they submitted or that is an error.

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.