Error with user click on cancel on file upload dialog

Multi tool use
Error with user click on cancel on file upload dialog
i have a input type file like this:
i handle onchange event to render the file in a modal; but i have an issues when user have selected a file that is in the input, and try to change it but being once in the dialog click on cancel it send error.
$(document).on('change', '.btn-file :file', function(evt) {
var size = this.files[0].size;
console.log(size);
});
This error:
Uncaught TypeError: Cannot read property 'size' of undefined
at HTMLInputElement.<anonymous> (func.js?20180702235402:11)
at HTMLDocument.dispatch (jquery.min.js?20180702235402:3)
at HTMLDocument.q.handle (jquery.min.js?20180702235402:3)
(anonymous) @ func.js?20180702235402:11
dispatch @ jquery.min.js?20180702235402:3
q.handle @ jquery.min.js?20180702235402:3
$(document).on('change', '.btn-file :file', function(evt) {
var size = this.files[0].size;
console.log(size);
});
https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
@Taplar work when you select a file. after that i you click and re open the dialog and click on cancel instead of select other file send error.
– walter nuñez
Jul 2 at 22:11
Ok, so then you just need to perform an if statement to make sure that the length of the files array is > 0. ezpz
– Taplar
Jul 2 at 22:13
1 Answer
1
You check if you have files
object or not. if so then get the size. otherwise fallback to 0 or something like that
files
$(document).on('change', '.btn-file :file', function(evt) {
var size = this.files[0] ? this.files[0].size : 0;
console.log(`size ${size}`);
});
https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Your snippet works fine for me. I choose a file and it console logged 85447.
– Taplar
Jul 2 at 22:08