jQuery check if all required inputs from a form are not empty

Viewed 22832

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?

6 Answers

I created this function which checks if the field is empty not only but if the user has inserted one or spaces without putting a character from a to b or other

function checkfield (champ)
{
var off='', isit=false;
for (var j=0; j <champ.val ().trim ().split (' ').length;j++)
{
off+=champ.val ().split (' ')[j];
}
off.replace (' ', '');
if (off.length==0) isit=true;
return isit;
}

to use :

example

if (checkfield ($('.class_of_field'))==true) return;
Related