xerox xerox - 4 months ago 12
jQuery Question

Selecting TD with specific classes from each TR and do math

I have a quite simple table.
Each TR with class "name-check" will be looped in php for as long as there are $name. Each new TR is getting a new class name with a counter, so basically the structures of the TR in this table looks like this:
Screenshot of table

<tr class="name-check name_1">
<tr class="name-check name_2">
<tr class="name-check name_3">
etc.


This is the content of each TR:

// Content of TR

<tr class="name-check name_1">
<td class="name">
<?php echo $name; ?>
</td>

<td class="check-date">
<label class="check-label"></label>
</td>

<td class="check-date">
<label class="check-label"></label>
</td>

<td class="check-date">
<label class="check-label"></label>
</td>

<td class="dont-count"></td>

<td class="check-date">
<label class="check-label"></label>
</td>


<td class="sum-up" align="center">
<span class="sum-up-span">0</span>
</td>
</tr>


This is the first TR which contains the TH:

// Table TH
<tr class="dates">
<th></th>
<th class="dat">1 </th>
<th class="dat">2 </th>
<th class="dat">3 </th>
<th class="dat">4 </th>
<th class="dont-count-th">Don't count</th>
</tr>

// Table TH End and after this tr comes:
<tr class="name-check name_1">...
<tr class="name-check name_2">
<tr class="name-check name_3">


When a user clicks on a TD with the class "check-date" that TD will get an extra class. Actually it is a click loop:
- 1 time click adds class .one,
- 2 time click adds class .two,
- 3 time click adds class .three.

What I want basically is, for each row, get the TD's which have any of these three classes and substract them from the number of TD's with the class of "check-date", or I could use the "TH" with class ".dat". The result should be displayed in the last td of each tr, the span with class ".sum-up-span".

I got that working for a single row, but multiple rows, it gets all the values.

var totalDays = $("tr.dates th.dat").length;
var daysOff = $("tr.name-check").each(function() {
$( "td.odsutan, td.godisnji, td.praznik" ).length;

var sum = totalDays - daysOff;

$(".sum-up-span").each(function () {
$(this).html("There " + sum + " from " + totalDays);
});


SOLVED
Both answers provided work great perfectly. Thank you guys for this.

Answer

Try this one,

$("td.check-date").click(function(e) {
    if($(this).hasClass("one"))
        $(this).removeClass("one").addClass("two");
    else if($(this).hasClass("two"))
        $(this).removeClass("two").addClass("three");
    else if($(this).hasClass("three"))
        $(this).removeClass("three");
    else
        $(this).addClass("one");

    var tr                  = $(this).closest("tr");
    var td_count            = tr.find("td.check-date").length;
    var clicked_td_count    = tr.find("td.check-date.one, td.check-date.two, td.check-date.three").length;

    tr.find("span.sum-up-span").text(td_count - clicked_td_count);
});