Logan Voss Logan Voss - 1 month ago 8
HTML Question

Can I use nextUntil to grab these values?

I want to take the

.text
or
.val
from some
<td>
s that are between
<tr>
s with a class
.ccc
and put it into an array.

<tr class="ccc">
<td>Strategy & Performance</td>
<td class="l_ccc_data" id="Foo~Q_1"></td> //the innerHTML of this should read 10
<td class="l_ccc_data" id="Foo~Q_2"></td> //the innerHTML of this should read 12
</tr>
<tr class="inner">
<td id="Bar~Q_1">5</td>
<td id="Bar~Q_2">6</td>
</tr>
<tr class="inner">
<td id="Something~Q_1">5</td>
<td id="Something~Q_2">6</td>
</tr>
<tr class="ccc">
<td>Central Engineering</td>
<td class="l_ccc_data" id="Boo~Q_1">Next total Goes here</td>
etc...


What I have for the script so far:

$(document).ready(function(){
$('.l_ccc_data').each(function(){
var id = $(this).attr('id');
var arr_id = id.split('~');
var q = arr_id[1];
var arr_sum = [];
arr_sum.push($(this).nextUntil('.ccc', '[id$="+q+"]').html()); //this could be .text(), or .val(), not sure
//then add up all the values in arr_sum and set
//$(this).html(whatever the sum);
});
});


I understand that encoding data into IDs is a bad idea, it's not really able to be helped currently. I need to get the values from any
<td>
that ends with the same Q_1 or Q_2 or whatever as my
<td>
with class
l_ccc_data
. Then I need to get that number, push it to an array, add them up, and have it be displayed in the innerhtml of that
<td>
with class
l_ccc_data
. A simple total. Shouldn't be this hard, but I feel like I'm missing something.

Is this the correct usage of nextUntil? What am I doing wrong?

Answer

The nextUntil method will look at the next siblings only, not at the next nodes that might have a different parent.

So you need to go one level up the DOM tree, from the current td to the parent tr, and then apply nextUntil. Then you need to go down again, for which you can use find.

Note that there were some errors which I corrected also (for instance the bad quoting in '[id$="+q+"]' which made the + not function as you intended). Note that you should not use html() for putting plain text. Use text() for that.

$(function(){
    $('.l_ccc_data').each(function(){
        var q = $(this).attr('id').split('~').pop();
        var sum = 0;
        $(this).parent().nextUntil('.ccc').find('[id$="'+q+'"]')
               .each(function () {
                    sum += +$(this).text();
               });
        $(this).text(sum);
    });
});