jQuery HTML5:如何从多输入字段中计算文件的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7139244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5: How to count the length of the files from the multiple-input field
提问by laukok
How can I use jquery to count the length of the files from the multiple-input field?
如何使用 jquery 计算多输入字段中文件的长度?
alert($('#myForm input[type=file]').files.length);
<input type="file" multiple="multiple" name="file[]"/>
error:
错误:
$("#myForm input[type=file]").files is undefined
$("#myForm input[type=file]").files 未定义
It works find with plain js but I don't want to use ID in my input field.
它适用于普通 js,但我不想在输入字段中使用 ID。
alert(document.getElementById('file').files.length);
<input type="file" multiple="multiple" name="file[]" id="file"/>
回答by Darin Dimitrov
Try getting the native DOM element using the .get
method:
尝试使用以下.get
方法获取原生 DOM 元素:
$('#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.
但是请注意,如果您有多个 DOM 元素与您的选择器匹配,这将返回第一个,如果您没有,它显然会抛出异常。
回答by Vlad
None of those answers work with the new html 5 multiple tag. So if you have something like
这些答案都不适用于新的 html 5 多重标签。所以如果你有类似的东西
<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.
注意multiple 标签,JQ 无法获取每个文件,只获取其中一个,我现在几乎尝试了所有可能的选择器,但无济于事。
However as mentioned before, standard Javascript works:
但是,如前所述,标准 Javascript 有效:
alert(document.getElementById('filesToUpload').files.length);
回答by Anantha Sharma
you can try
alert($('#myForm input[type=file]').length);
or
alert($('#myForm input[type=file]').size());
你可以尝试
alert($('#myForm input[type=file]').length);
或
alert($('#myForm input[type=file]').size());
or alert($('#file').size());
or alert($('#file').length);
或alert($('#file').size());
或alert($('#file').length);