Cameron
Cameron

Reputation: 28783

jQuery when all elements have a class do something

I have any number of elements on a page with a class of choice e.g.

<div class="choice"></div>
<div class="choice"></div>

When I run a function it adds a class of done to the the div so they become:

<div class="choice done"></div>

Within this same function each time it runs I'm then going to check how many of those choices have the class of done on them and when they all have it I'm going to run another function.

This is what I have done so far:

function addDone(element) {

$num = 0;

$(element).addClass('done');

$('.choice').each(function() {
    if($(this).hasClass('done')) {
        $num + 1;
    }
});

if($num >= $('.choice').length) {
    alert('all done...');
}

}

But it runs the alert as soon as I call the function... so not working properly, any ideas on what the problem is or better solutions to do this?

Note: That in the real app each choice has an id when is what goes in place of the element variable used in the function!

Upvotes: 1

Views: 3273

Answers (3)

gdoron
gdoron

Reputation: 150253

if (!$(".choice:not(.done)").length)
    // do your magic here.

Upvotes: 1

Frettman
Frettman

Reputation: 2271

$num + 1;

should probably be

$num = $num + 1;

Apart from that there may be better solutions as others have suggested.

Upvotes: 2

Steve Greatrex
Steve Greatrex

Reputation: 15999

You could rephrase this as:

do something when there are no elements with choice but without done

In which case, the following is a little neater:

if (!$(".choice").not(".done").length) {
    alert("all done");
}

Working Fiddle

Upvotes: 5

Related Questions