Link to home
Start Free TrialLog in
Avatar of impressionexpress
impressionexpress

asked on

Get all instance of class invalid in jquery

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
}
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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