I've got a simple table that allows users to enter 2 numbers, and then a script then calculates the annual average and gets the totals for all rows that have the same option in the select menu.
I've setup a sample JSFiddle:
http://jsfiddle.net/fmdataweb/73Jzc/1/
that shows how this works. I've just noticed that at times I get a strange rounding error (I want it to round to one decimal place). For example if you select "moderate" and then enter 5 and 4 for an average of 0.4, then click the button to create a new row and select "moderate" again then enter 3 and 40 for an average of 2.3 you'll notice the total for the moderate is "2.6999999999999997" when it should be 2.7.
If you enter other numbers it's fine so far in my testing but for some reason these combinations don't get rounded for the totals and I'm not sure why. Appreciate if anyone can point out the error in my script. Here's the script that does the averages and totals:
$('#nextYear')
.on('change', 'select', calc)
.on('keyup', 'input', calc);
function calc(){
$('#nextYear tr:has(.risk)').each(function(i,v){
var $cel = $(v.cells);
var $risk = $cel.eq(1).find('option:selected').val();
var $numb = $cel.eq(2).find('input').val();
var $weeks = $cel.eq(3).find('input').val();
var $avg = ($numb * $weeks) / 52;
var $avgRounded = Math.round( $avg * 10 ) / 10;
$cel.eq(4).find('input').val($avgRounded);
});
var tot = {};
$('#nextYear tr:has(.risk) option:selected')
.map(function(i){
var el = $(this).val();
var qty = parseFloat($('#nextYear tr:has(.risk)').eq(i).find('td:last').prev().find('input').val());
if (!tot.hasOwnProperty(el)) {
tot[el] = 0;
}
tot[el] += qty
return tot;
}).get();
// console.log(tot);
$('#textfield6').val(tot.moderate);
$('#textfield7').val( tot.high );
}