Imagine a simple form with method POST
and 30 inputs.
I would like to create a jQuery function that will be called from submit button. I searched about how to check all inputs that are required, but didn't find anything to help.
I would like something like this:
var inputs_required = all inputs from my form which have attribute required;
function check_required_inputs() {
if(inputs_required != "") {
//create ajax with serialize() and submit form;
}
} else {
//highlight inputs that are empty and show a message;
}
Can this be achieved in jQuery?
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.
}