jQuery:查找所有可见的必填字段

问题描述:

我正在尝试查找所有具有required属性的字段,它们也应为visible.因为页面也可以隐藏必填字段.这是我尝试过的:

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:

function validateRequiredFields()
{
    $('input,textarea,select').attr('required',true).filter(':visible:first').each(function(i, requiredField){

        if($(requiredField).val()=='')
        {
            alert($(requiredField).attr('name'));
        }
    });
}

如果要查找输入,文本区域或选择具有属性required且为visible的元素,请使用

If you want to find input, textarea,or select elements that have the attribute required and are visible use the has attribute selector:

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

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