Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Find all the visible required fields

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'));
        }
    });
}
like image 603
Himanshu Yadav Avatar asked Sep 06 '13 14:09

Himanshu Yadav


People also ask

Which jQuery filter can be used to check if element is visible?

Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not.

Is visible selector jQuery?

The :visible selector in jQuery is used to select every element which is currently visible. It works upon the visible elements. The elements that are consuming space in the document are considered visible elements. The height and width of visible elements are larger than 0.


1 Answers

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')

or

$(':input[required]:visible')//might be little costlier
like image 153
Arun P Johny Avatar answered Oct 07 '22 21:10

Arun P Johny