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'));
}
});
}
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With