jQuery:查找所有可见的必填字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18659726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: Find all the visible required fields
提问by Himanshu Yadav
I am trying to find all the fields with required
attribute and they should be visible
too. Because page can have hidden required fields too. Here is what I tried:
我试图找到所有具有required
属性的字段,它们也应该visible
如此。因为页面也可以隐藏必填字段。这是我尝试过的:
function validateRequiredFields()
{
$('input,textarea,select').attr('required',true).filter(':visible:first').each(function(i, requiredField){
if($(requiredField).val()=='')
{
alert($(requiredField).attr('name'));
}
});
}
回答by Arun P Johny
If you want to find input, textarea,or select elements that have the attribute required
and are visible
use the has attribute selector:
如果要查找具有属性required
并visible
使用has 属性选择器的input、textarea 或 select 元素:
$('input,textarea,select').filter('[required]:visible')
or
或者
$(':input[required]:visible')//might be little costlier