JQuery检查输入文件
问题描述:
我在下面的组中有文件输入字段。我希望他们都是必填字段。JQuery检查输入文件
<!-- file upload group -->
<div class="Fieldset FileUpGroup">
<span class="Legend">File Upload Group: (required)</span>
<input name="fileUploads[]" type="file">
<input name="fileUploads[]" type="file">
<input name="fileUploads[]" type="file">
</div>
我有以下JQuery来验证,但它只验证第一个。
$('.FileUpGroup').each(function() {
if($(this).find('input[type=file]').val() == '') {
Response('- Upload file not selected!', true);
$(this).addClass('Error').fadeOut().fadeIn();
return false;
}
else {
$(this).removeClass('Error');
}
});
谢谢!
答
你是错误的元素上使用each()
:
$('input[type="file"]').each(function() {
var $this = $(this);
if ($this.val() == '') {
Response('- Upload file not selected!', true);
$this.addClass('Error').fadeOut().fadeIn();
return false;
} else {
$this.removeClass('Error');
}
});
答
.val()
只返回第一个值。
在您的循环中($('.FileUpGroup').each)
仅针对一个项目激活... DIV.FileUpGroup
元素。 $('.FileUpGroup input[type=file]')
会找到所有的项目,然后一次迭代它们一个
这里是一个例子。希望我一直很有用。
$('.FileUpGroup input[type=file]').each(function() {
if($(this).val() === '') {
// wabba dabba do
}
else {
// badda bawwa do
}
});
谢谢!它工作真棒。 – user1108996 2011-12-25 07:37:02
很高兴帮助:) – AlienWebguy 2011-12-26 03:02:23
工作很好。非常感谢。 – 2013-12-29 05:05:10