This is a related question to one I posted earlier... I'm trying to sum all the input elements that begin with 'pull' and place that total in the 'totalpull' input field. I have that part working. Now, I'm trying to calculate the average if a user enters something manually in the 'totalpull' input field and set each 'pull' input to that value. Trying below, but it doesn't work...
//This is the sum formula, which works
$('input[name^=pull]').bind('keyup', function() {
$('#totalpull').val( $('input[name^=pull]').sumValues() );
});
$.fn.sumValues = function() {
var sum = 0;
$("input[name^='pull']").each(function() {
if ( $(this).is(':input') ) {
var val = $(this).val();
} else {
var val = $(this).text();
}
sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10 );
});
return sum;
};
//This is the avg formula, which does not work
//Keep getting v / rowCount.replace is not a function
$('input[name=totalpull]').bind('keyup', function() {
$('input[name^=pull]').each(function() {
$(this).val( $('input[name=totalpull').avgValues() );
});
});
$.fn.avgValues = function() {
var avg = 0;
var v = $("input[name=totalpull").val();
var rowCount = $("#convertRow tr").length;
avg += parseFloat( (v / rowCount).replace(/[^0-9-\.]/g, ''), 10);
return avg;
}
<table id="convert">
<tbody>
<tr><td><input type="text" value="" name="pull0" /></td></tr>
<tr><td><input type="text" value="" name="pull1" /></td></tr>
<tr><td><input type="text" value="" name="pull2" /></td></tr>
<tr><td><input type="text" value="" name="pull3" /></td></tr>
</tbody>
<tfoot>
<input type="text" id="totalpull" name="totalpull" value="" />
</tfoot>
</table>