Reputation: 231
I'm using this function to total the sum of all values in a column. I would like to have the results display in an input box as well as to the cell that it currently does. I'm just a little stuck on the syntax for mixing the two since one needs to reference a value.
JQuery
$(document).ready(function(){
$('#front_finish, #back_finish').change(function(){
function tally (selector) {
$(selector).each(function () {
var total = 0,
column = $(this).siblings(selector).andSelf().index(this);
$(this).parents().prevUntil(':has(' + selector + ')').each(function () {
total += parseFloat($('td.sum:eq(' + column + ')', this).html()) || 0;
})
$(this).html(total);
});
}
tally('td.total');
});
});
Input
<input type="text" name="glass_total" id="glass_total" value="0" />
Table
<table id="data">
<tr>
<th>Finish</th>
<th>Pattern</th>
<th>Price</th>
</tr>
<tr>
<td>Front Finish:</td>
<td><span id="front_finish_name">Mirror</span></td>
<td class="sum" id="front_finish_price">15</td>
</tr>
<tr>
<td>Front Pattern:</td>
<td><span id="front_pattern_name"></span></td>
<td class="sum" id="front_pattern_price"></td>
</tr>
<tr>
<td>Back Finish:</td>
<td><span id="back_finish_name">Mirror</span></td>
<td class="sum" id="back_finish_price">15</td>
</tr>
<tr>
<td>Back Pattern:</td>
<td><span id="back_pattern_name"></span></td>
<td class="sum" id="back_pattern_price"></td>
</tr>
<tr>
<th colspan="2" align="right">Total</th>
<td class="total"></td>
</tr>
Upvotes: 1
Views: 116
Reputation: 5800
I think your jquery may be a little off. Try this:
$(document).ready(function () {
$('#front_finish, #back_finish').change(function () {
var total = 0, temp;
$("#data td.sum").each(function () {
temp = $(this).html();
if (!temp) {
return;
}
temp = parseFloat(temp);
if (isNaN(temp)) {
return;
}
total += temp;
});
$("#data td.total").html(total);
$("#glass_total").val(total); // if you want it in the textbox
});
});
Upvotes: 1
Reputation: 78710
I'm a bit confused by the each as the html you posted only has one td.total
. If there really is just one then all you have to do is this:
$("#glass_total").val(total);
If there are multiple you'll need to explain a bit more since the input appears to be unique.
Upvotes: 1