我的表单很简单,输入方式如下:
<input id="my_id" multiple="true" type="file" name="image_name[]" />
现在我有两个问题:
答案 0 :(得分:12)
如果input type file
,则值array
与[{1}} files
一起存储,密钥为name
。
$('input#my_id').change(function(){
var files = $(this)[0].files;
if(files.length > 10){
alert("you can select max 10 files.");
}else{
alert("correct, you have selected less than 10 files");
}
});
答案 1 :(得分:1)
纯javascript:
document.getElementById("my_id").addEventListener("change", function() {
console.log(this.files.length);
});
答案 2 :(得分:-1)
<input multiple="multiple" id="s" type="file" />
要获取所选文件的数量,请使用 element.files.length
let ele =document.getElementById("s");
console.log(ele.files.length); // logs number of files selected
验证
/*
Validates number of files selected
selectedFilesLength - number of files selected - ( ele.files.length )
return true if minimumNumberOfFiles <= selectedFilesLength <= maximumNumberOfFiles
*/
function validate(selectedFilesLength, acceptableLengthRange) {
return (selectedFilesLength >= acceptableLengthRange[0] && selectedFilesLength <= acceptableLengthRange[1]);
}
// example 1 to 10 files
if(validate(document.getElementById("s").length,[1,10])){
alert("OK");
}
else{
alert("Limit exceeded");
}
上述网站中提供了一个实时示例
答案 3 :(得分:-1)
使用 vanila js
if(document.getElementById("my_id").files.length > 10){
console.log("10 files can be uploaded at a time.");
}