Reputation: 27
I am newbie in javascript and cakephp. I have added a new row using javascript and now I want to calculate the sum of the column "amount" whenever I fill the amount field. HTML code for adding new field :
<table id="voucher_line" style="width:750px; font-size:13px;">
<tr>
<th>Others Component</th>
<th>Others GoB</th>
<th>Amount</th>
</tr>
<tr id="voucher_">
<td style="width:150px;"><?php echo $this->Form->input('DebitVoucherLine.0.coa_component_id',array('options'=>$coa_components,'type'=>'select','label'=>false));?></td>
<td style="width:150px;"><?php echo $this->Form->input('DebitVoucherLine.0.level_five_id',array('type'=>'select','label'=>false));?></td>
<td style="width:204px;"><?php echo $this->Form->input('DebitVoucherLine.0.amount', array('label'=>false, 'type'=>'text'));?></td>
</tr>
And the javascript:
<script type="text/javascript">
$(":button#add").click(function() {
var clonedRow = $("#voucher_line tr:last").clone();
var newIndex = (document.getElementById('voucher_line').rows.length-1);
clonedRow[0].id = 'voucher_' + newIndex;
$.each($('input, select', clonedRow), function(i, val){
val.name = val.name.replace((newIndex - 1), newIndex);
val.id = val.id.replace((newIndex - 1), newIndex);
val.value = '';
})
$("#voucher_line").append(clonedRow);
});
$(":button#remove").click(function(){
if ($("#voucher_line tr").length != 2) {
$("#voucher_line tr:last").remove();
}
});
</script>
Any help would be appreciated. Thanks in advance.
Upvotes: 1
Views: 2284
Reputation: 8390
You could iterate over all lines in the table and calculate the value. Here's a quick example:
function calculateTableTotal() {
var total = 0;
$('#voucher_line tr td input[type="text"]').each(function() {
// find the amount input field
var $input = $(this);
total += parseInt($input.val());
});
alert('The total is : ' + total);
}
Upvotes: 1