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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:09:54  来源:igfitidea点击:

jQuery: Find all the visible required fields

javascriptjquery

提问by Himanshu Yadav

I am trying to find all the fields with requiredattribute and they should be visibletoo. 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 requiredand are visibleuse the has attribute selector:

如果要查找具有属性requiredvisible使用has 属性选择器的input、textarea 或 select 元素:

$('input,textarea,select').filter('[required]:visible')

or

或者

$(':input[required]:visible')//might be little costlier