jQuery check if all required inputs from a form are not empty
Zakaria already posted an answer, which should work great. Alternatively, instead of having a custom class, you could instead find all input
, textarea
and select
elements that have the attribute required
and are visible
using
var required = $('input,textarea,select').filter('[required]:visible');
And then iterate through them using each()
etc.
Example:
var allRequired = true;
required.each(function(){
if($(this).val() == ''){
allRequired = false;
}
});
if(!allRequired){
//DO SOMETHING HERE... POPUP AN ERROR MESSAGE, ALERT , ETC.
}
You could give all your required inputs a common class (required
for example) then use each()
to loop through them like :
function check_required_inputs() {
$('.required').each(function(){
if( $(this).val() == "" ){
alert('Please fill all the fields');
return false;
}
});
return true;
}
jQuery('button').on('click', function() {
jQuery('input:invalid').css('background-color','red');
jQuery('input:valid').css('background-color','green');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" required="true" />
</form>
<button>click</button>
You simply give the inputs the required="true"
attribute, then all empty required inputs will have the pseudo class :invalid
.
jQuery('input:invalid')
gives you a list of all invalid inputs. .length
will give you the length of said list, if the length is > 0, your form is invalid.