[英]Count empty file upload controls
在一組動態生成的文件上傳控件中:
<input type="file" name="archivos[]">
<input type="file" name="archivos[]">
<input type="file" name="archivos[]">
// ...
...我可以輕松地算出非空的:
// Works fine
var nonEmptyCount = $("input[type='file'][name='archivos[]'][value!='']").length;
但是,當我嘗試計算空值 (我真正需要的)時,選擇器永遠不會匹配任何內容:
// Always zero
var emptyCount = $("input[type='file'][name='archivos[]'][value='']").length;
我不敢相信我需要這個繁瑣的代碼:
// Works but ugly
var emptyCount = $("input[type='file'][name='archivos[]']").length -
$("input[type='file'][name='archivos[]'][value!='']").length;
我缺少什么?
一種解決方案是檢查迭代器中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' />
您可以通過以下方式過濾它們:
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[]">
我沒有任何解釋(我將立即接受提供答案的任何答案),但根本原因似乎是使用泛型屬性equals選擇器來找到控件:
$("input[type='file']")
如果我使用jQuery擴展快捷方式 ,則其他所有功能都可以正常運行:
$("input:file")
根據文檔:
[type='file']
應該表現更好 ...因此某處必須有一個錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.