Jaakko Karhu
Jaakko Karhu

Reputation: 2386

How to have "and" and "or" conditions in jQuery selector

I would like to check if two separate divs are returning true with hasClass.

    if($('#first-name, #last-name').hasClass('has-focused')) {
        $('#personal-info').valid();
    }

This checks if either one has class 'has-focused'.

Instead I could do something like this:

    if($('#first-name').hasClass('has-focused')&&$('#last-name').hasClass('has-focused')) {
        $('#personal-info').valid();
    }

However, that solution feels a bit clumsy. So is it possible to do something like this.

    if($('#first-name'&&'#last-name').hasClass('has-focused')) {
        $('#personal-info').valid();
    }

Upvotes: 1

Views: 52

Answers (3)

KAD
KAD

Reputation: 11112

You can use filter for the class name and length property to check if both have the class

if ($('#first-name, #last-name').filter(".has-focused").length == 2){
  $('#personal-info').valid();
}

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You can't do that, though you can have a filter based solution like

if ($('#first-name, #last-name').not('.has-focused').length == 0) {
  $('#personal-info').valid();
}

Upvotes: 3

Zamboney
Zamboney

Reputation: 2010

try something like this

$('#first-name.has-focused,#last-name.has-focused').length === 2

Upvotes: 0

Related Questions