HTML5: How to count the length of the files from t

2019-01-20 02:04发布

问题:

How can I use jquery to count the length of the files from the multiple-input field?

alert($('#myForm input[type=file]').files.length);
<input type="file" multiple="multiple" name="file[]"/>

error:

$("#myForm input[type=file]").files is undefined

It works find with plain js but I don't want to use ID in my input field.

alert(document.getElementById('file').files.length);

<input type="file" multiple="multiple" name="file[]" id="file"/>

回答1:

Try getting the native DOM element using the .get method:

$('#myForm input[type=file]').get(0).files.length

Note however that if you have multiple DOM elements matching your selector this will return the first one and if you have none it will obviously throw an exception.



回答2:

None of those answers work with the new html 5 multiple tag. So if you have something like

<input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" size="20" />

note the multiple tag, JQ fails at getting every one of this files, only gets one of them, I've pretty much tried all of the possible selectors now but to no avail.

However as mentioned before, standard Javascript works:

 alert(document.getElementById('filesToUpload').files.length);


回答3:

you can try alert($('#myForm input[type=file]').length); or alert($('#myForm input[type=file]').size());

or alert($('#file').size()); or alert($('#file').length);