Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 699
Bogdan C Avatar asked Nov 28 '17 12:11

Bogdan C


People also ask

How do you check if all inputs are not empty with jQuery?

Just use: $("input:empty"). length == 0; If it's zero, none are empty.

How do you check if all form fields are filled?

$('#dynamic-form-fields input:required'). each(function() { if ($(this). val() === '') alert('error please fill all fields! '); });

How check form is empty or not in jQuery?

each(function() { if ($(this). val() != "") { empty = false; return false; } }); This should look all the input and set the empty var to false, if at least one is not empty.


2 Answers

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.
}
like image 146
SuperMrBlob Avatar answered Oct 19 '22 23:10

SuperMrBlob


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;
}
like image 33
Zakaria Acharki Avatar answered Oct 19 '22 23:10

Zakaria Acharki