我试图检查图像类型的多个文件上传值。有了这个html:
<input type="file" name="image" id="fileUpload">
这是js:
document.getElementById('fileUpload').onchange = function () {
var filename = this.value;
var a = filename.split(".");
if( a.length === 1 || ( a[0] === "" && a.length === 2 ) ) {
return "";
}
var suffix = a.pop().toLowerCase();
//if( suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'gif' && suffix != 'tiff'){
if (!(suffix in {jpg:'', jpeg:'', png:'', gif:'', tiff:''})){
document.getElementById('fileUpload').value = "";
alert('Please select an image.');
}
};
以上工作正常。但有多个输入:
<input type="file" name="image" id="fileUpload">
<input type="file" name="image" id="fileUpload">
<input type="file" name="image" id="fileUpload">
它只适用于第一个。我尝试使用getElementsByClassName
更改为类,但是没有这样做,也没有将它包装在函数中并使用
<input type="file" name="image" id="fileUpload" onchange="checkForImageType()">
答案 0 :(得分:2)
您不能拥有多个具有相同ID的elemet,文档中元素的ID必须是唯一的。
您可以使用类对类似元素进行分组,然后使用类选择器。
由于您使用了jQuery标记
<input type="file" name="image" class="fileUpload">
<input type="file" name="image" class="fileUpload">
<input type="file" name="image" class="fileUpload">
然后
jQuery(function($){
var regex = /.\.(jpg|jpeg|png|gif|tiff)$/i;
$('.fileUpload').change(function () {
var filename = this.value;
if (!regex.test(filename)) {
$(this).replaceWith($(this).clone(true, true));// this.value = "" - does not work with IE
//see http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery
alert('Please select an image.');
}
});
})
演示:Fiddle
答案 1 :(得分:2)
由于id
必须是唯一的,因此您需要为input
使用类:
<input type="file" name="image" id="fileUpload">
<input type="file" name="image" id="fileUpload">
<input type="file" name="image" id="fileUpload">
然后您可以使用 document.getElementsByClassName 代替document.getElementById
:
var fileUpload = document.getElementsByClassName('fileUpload');
for (var i = 0; i < fileUpload.length; i++) {
fileUpload[i].onchange = function () {
var filename = this.value;
var a = filename.split(".");
if (a.length === 1 || (a[0] === "" && a.length === 2)) {
return "";
}
var suffix = a.pop().toLowerCase();
//if( suffix != 'jpg' && suffix != 'jpeg' && suffix != 'png' && suffix != 'gif' && suffix != 'tiff'){
if (!(suffix in {
jpg: '',
jpeg: '',
png: '',
gif: '',
tiff: ''
})) {
this.value = "";
alert('Please select an image.');
}
}
}
<强> Fiddle Demo 强>