Get all instance of class invalid in jquery

impressionexpress
impressionexpress used Ask the Experts™
on
I need to loop through form elements (Textboxes, Selectboxes, checkboxes) and find if any of the elements has class invalid.
if(invalid class){
           $("html, body").animate({ scrollTop: 0 }, 1000);
}
else{
        // submit form
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Hi there,

Something like this should do it:

if ($('input, select').hasClass('invalid')) {
    console.log("We have some invalid inputs");
} else {
    console.log("Everything is good");
}

Open in new window

leakim971Multitechnician
Top Expert 2014

Commented:
function checkForm() {
var formNotValid = $("[name].invalid").length > 0;
if( formNotValid ) {
   $("html, body").animate({ scrollTop: 0 }, 1000);
   return false; // prevent form to submit
}
return true; // submit form

Open in new window


<form onsubmit="return checkForm()" >

Open in new window


you can also use :

$("form").on("submit", function(event) { // with <form action="blabla"> no onsubmit attribute this time
  checkFormElements(); // this function check first name, last name, birthdate and so on...
  var formNotValid = $("[name].invalid").length > 0;
  if( formNotValid ) {
     $("html, body").animate({ scrollTop: 0 }, 1000);
     event.preventDefault();
  }

});

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial