0

I'd like to add the sum of hours in a week using jquery from a table, when text fields change the total in div total_amount should be updated, but it doesn't seem to be working.

$(function() {
$("[id$=day]").change(function() {

var total = 0;
$('table input[id$=day]').each(function() {
    var sum_id = this.id;
    total[this.value] += parseInt($('#' + sum_id).val(), 10);
});

    $('div.total_amount').html(total);
});
});

And the html is here

<td class="timesheet2"><input type="text" name="daymon" id="monday">
</td>

<td class="timesheet2"><input type="text" name="daytue" id="tuesday">
</td>

<td class="timesheet2"><input type="text" name="daywed" id="wednesday">
</td>

<td class="timesheet2"><input type="text" name="daythurs" id="thursday">
</td>

<td class="timesheet2"><input type="text" name="dayfri" id="friday">
</td>

<td class="timesheet2"><input type="text" name="daysat" id="saturday">
</td>

<td class="timesheet2"><input type="text" name="daysun" id="sunday">
</td>

<td class="timesheet"><div id="total_amount"></div>
</td>
RJMB
  • 43
  • 2
  • 7

2 Answers2

0

This could be better I think.

var sum = 0;
    $('.timesheet2').each(function() {
        sum += Number($(this).val());
    });

    $('#total_amount').html(sum);
});​​​​​​​​​
Muhammad Hani
  • 8,476
  • 5
  • 29
  • 44
  • Your selector is incorrect, it needs an input selector as well as the .timesheet2 selector: $('.timesheet2 input').each.... – Lowkase Mar 12 '13 at 14:22
0

You had a problem showing the final value. You were using a class selector when you needed an ID.

http://jsfiddle.net/YE5vF/2/

HTML

<table>
<tr>
<td class="timesheet2"><input type="text" name="daymon" id="monday"></td>
<td class="timesheet2"><input type="text" name="daytue" id="tuesday"></td>
<td class="timesheet2"><input type="text" name="daywed" id="wednesday"></td>
<td class="timesheet2"><input type="text" name="daythurs" id="thursday"></td>
<td class="timesheet2"><input type="text" name="dayfri" id="friday"></td>
<td class="timesheet2"><input type="text" name="daysat" id="saturday"></td>
<td class="timesheet2"><input type="text" name="daysun" id="sunday"></td>
<td class="timesheet"><div id="total_amount"></div></td>
</tr>
</table>

JS

$("[id$=day]").change(function() {
    var total = 0;     
    $('.timesheet2 input').each(function() {
        total = total + Number( $(this).val() );
    });
    $('div#total_amount').html(total); 
});
Lowkase
  • 5,631
  • 2
  • 30
  • 48