h3tr1ck
h3tr1ck

Reputation: 909

JQuery not grabbing HTML data

I have the following HTML table displayed on my webpage.

<div class="timecard">
<table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;">
    <tbody>
        <tr class="display_row odd">
            <td align="left" class="job_code" style="color:#000099">2400-Orchard</td>
            <td align="right">9:47am</td>
            <td align="right">5/19/2014</td>
            <td align="right" class="hrs">01:00</td>
        </tr>
        <tr class="display_even odd">
            <td align="left" class="job_code" style="color:#000099">1500-Emerald</td>
            <td align="right">12:37am</td>
            <td align="right">5/17/2014</td>
            <td align="right" class="hrs">0:30</td>
        </tr>
    </tbody>
</table>
</div>

<div id="total"></div>

Then I have the following jquery script that grabs the total times for each job_code and adds them up and displays them. However, it does not seem to be working properly. It isn't displaying the totals added up by the jQuery statement underneath the HTML table as it should be.

$(document).ready(function () {

var timeString = $(this).next('td.hrs').text();
var components = timeString.split(':');
var seconds = components[1] ? parseInt(components[1], 10) : 0;
var hrs = parseInt(components[0], 10) + seconds / 60;
total += hrs;

var temp = [];
$('.job_code').each(function (index, element) {
    var text = $(this).text();
    temp.push(text);
});

// remove duplicates
var job_code = [];
$.each(temp, function (index, element) {
    if ($.inArray(element, job_code) === -1) job_code.push(element);
});

var sum = {};
$.each(job_code, function (index, element) {
    var total = 0;
    $('.job_code:contains(' + element + ')').each(function (key, value) {
        var timeString = $(this).siblings('td.hrs').text();
        var components = timeString.split(':');
        var seconds = components[1] ? parseInt(components[1], 10) : 0;
        var hrs = parseInt(components[0], 10) + seconds / 60;
        total += hrs;
        sum[index] = {
            'job_code': element,
                'total': total
        };
    });
});

console.log(sum);

$.each(sum, function (index, element) {
    $('#total').append('<p>Total for ' + element.job_code + ': ' + element.total + '</p>');
});

});

http://jsfiddle.net/2D5fb/1/

Any ideas are greatly appreciated. Thanks.

Upvotes: 1

Views: 101

Answers (1)

j08691
j08691

Reputation: 207901

Aside from total not being defined, change:

var timeString = $(this).next('td.hrs').text();

to

var timeString = $(this).siblings('td.hrs').text();

.next() literally only looks at the next element and td.hrs isn't the next one. .siblings() however will run through all the siblings.

jsFiddle example

Upvotes: 2

Related Questions