9

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?

2
  • if your form has inputs with required you cannot submit the form and a message is show already by html5. you form will have a :valid and :invalid state to access via css Commented Nov 28, 2017 at 13:03
  • I know. You are right. As long as an input with attribute required is not filled, html5 should return error and highlight that error. Still, my form is submiting through ajax and the submit script is executing. Commented Nov 28, 2017 at 13:18

6 Answers 6

19

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.
}
Sign up to request clarification or add additional context in comments.

3 Comments

This is so simple and useful. With the :visible selector we make sure it gets only the inputs from the current tab.
This is an elegant answer to be certain.
great :) just note that the example will not work for select, as .val() does not provide value of select - need to get option:selected.
12

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;
}

Comments

5

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.

Comments

0

you can try this assume that the form has an ID of form-action and submit button of ID form- submit.

var submitButton = $('#form-submit'),
    formContainer  = $('#form-action');

    submitButton.on('click',function(e){
      e.preventDefault();
      formContainer.find('input').each(function(index,ele){
        if(ele.value === null || ele.value === ''){
            var error  = " the " + ele.name + " field  is requird ";
                ele.after(error);
           }
     });
});   

Comments

0

You could also leverage the iterable function, every(), which will either return true only if every input validation is satisfied or false if otherwise:

function check_required_inputs() {
   var valid =  Array.prototype.every.call($('.required'), function(input) {
     return input.value;
   });

   if (valid) {
     return true;
   } else {
     alert('Please fill all the fields');

     return false;
   }
}

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.