user3758114
user3758114

Reputation: 47

Search page for class .has-error

So I have built some validation in Javascript and when a field has an error the div <div class="form-group">...</div> becomes <div class="form-group has-error">...</div>

I then have a .btn-bar div that contains the button for submitting the form. I have this hidden by default when the page loads:

$(document).ready(function(){
    $('.registration-information').hide();
    $('.btn-bar').hide();
});

I have a function to show the .btn-bar:

function enableButtons(){
  if(noErrors){
    $('.btn-bar').slideDown();
  }
}

Now obviosuly, the script above doesn't work. More specifically, the if statement. My question, is how do I search for a div that has has-error in the class name on the page? If there is one then the btn-bar does not show, if there isn't any then the btn-bar shows.

Upvotes: 1

Views: 439

Answers (2)

Jason M. Batchelor
Jason M. Batchelor

Reputation: 2951

It's actually fairly simple in jQuery. Try something like this:

function noErrors() {
    return $('.has-error').length == 0;
}

function enableButtons(){
    if(noErrors()){
        $('.btn-bar').slideDown();
    }
}

I separated noErrors() into its own function, in case there are other validation tests you eventually want to add in that aren't related just to the .has-error class.

Good luck!

Upvotes: 1

CRABOLO
CRABOLO

Reputation: 8793

You can achieve this simply by doing this :

$(document).ready(function(){
    $('.registration-information').hide();
    $('.btn-bar').hide();

    if (!$('.has-error')) {
        $('.btn-bar').slideDown();
    }
});

It will check to see if any element has the class .has-error , and if it does not ! exist anywhere on the page, it will show the .btn-bar.

Upvotes: 0

Related Questions