[英]Count empty file upload controls
In a dynamically generated set of file upload controls: 在一组动态生成的文件上传控件中:
<input type="file" name="archivos[]">
<input type="file" name="archivos[]">
<input type="file" name="archivos[]">
// ...
... I can easily count the non-empty ones: ...我可以轻松地算出非空的:
// Works fine
var nonEmptyCount = $("input[type='file'][name='archivos[]'][value!='']").length;
However, when I try to count the empty ones (what I actually need) the selector never matches anything: 但是,当我尝试计算空值 (我真正需要的)时,选择器永远不会匹配任何内容:
// Always zero
var emptyCount = $("input[type='file'][name='archivos[]'][value='']").length;
I can't believe I need this cumbersome code: 我不敢相信我需要这个繁琐的代码:
// Works but ugly
var emptyCount = $("input[type='file'][name='archivos[]']").length -
$("input[type='file'][name='archivos[]'][value!='']").length;
What bit am I missing? 我缺少什么?
One solution is to check if value is empty inside an iterator like: 一种解决方案是检查迭代器中value是否为空,例如:
$("#findEmpty").on("click", function() { var count = 0; $(":file[name='archivos[]']").each(function() { if (this.value == "") { count++; } }); alert(count); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" name="archivos[]" /> <input type="file" name="archivos[]" /> <input type="file" name="archivos[]" /> <input type="file" name="archivos[]" /> <input type="file" name="archivos[]" /> <input type="file" name="archivos[]" /> <input type='button' value='Check Empty' id='findEmpty' />
You can filter them this way: 您可以通过以下方式过滤它们:
var emptyOne = $("input[type='file'][name='archivos[]']").filter(function () {
return $(this).val() == "";
});
$(function () { var emptyOne = $("input[type='file'][name='archivos[]']").filter(function () { return $(this).val() == ""; }); alert(emptyOne.length); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <input type="file" name="archivos[]"> <input type="file" name="archivos[]"> <input type="file" name="archivos[]">
I don't have an explanation (and I'll immediately accept any answer that provides one) but the root cause seems to be using the generic attribute equals selector to find the controls: 我没有任何解释(我将立即接受提供答案的任何答案),但根本原因似乎是使用泛型属性equals选择器来找到控件:
$("input[type='file']")
If I use the jQuery extension short-cut , everything else works as expected: 如果我使用jQuery扩展快捷方式 ,则其他所有功能都可以正常运行:
$("input:file")
As per the docs: 根据文档:
[type='file']
should perform better [type='file']
应该表现更好 ... so there must be a bug somewhere. ...因此某处必须有一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.