2011-12-25 151 views
5

我在下面的组中有文件输入字段。我希望他们都是必填字段。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'); 
    } 
}); 

谢谢!

回答

9

你是错误的元素上使用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'); 
    } 
}); 
+0

谢谢!它工作真棒。 – user1108996 2011-12-25 07:37:02

+0

很高兴帮助:) – AlienWebguy 2011-12-26 03:02:23

+0

工作很好。非常感谢。 – 2013-12-29 05:05:10

0

.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 
    } 
});