我已经创建了一个表来实时计算几个字段的总数。我在表后面有一个名为amount的输入字段,如何使其值也实时更新为相同的值表中的总计。表示如果表中的总计为10,则表格中的此值也应更改为10.
见小提琴: http://jsfiddle.net/hSxkW/48/
HTML:
<table>
<thead>
<tr>
<th>VARIABLE</th>
<th>QTY</th>
<th>PRICE</th>
<th>SUM</th>
</tr>
</thead>
<tbody>
<tr>
<td>Millage</td>
<td><input class='qty' size='1'/></td>
<td class='price'>1.25</td>
<td class='sum'>0</td>
</tr>
<tr>
<td> Number of vans</td>
<td><input class='qty' size='1'/></td>
<td class='price'>2.10</td>
<td class='sum'>0</td>
</tr>
<tr>
<td colspan='2'>Total</td>
<td id='total'></td>
</tr>
</tbody>
</table>
<form action="">
<input name="amount" value="0.00">
</form>
Jquery的:
function getTotal(){
var total = 0;
$('.sum').each(function(){
total += parseFloat(this.innerHTML)
});
$('#total').text(total);
}
getTotal();
$('.qty').keyup(function(){
var parent = $(this).parents('tr');
var price = $('.price', parent);
var sum = $('.sum', parent);
var value = parseInt(this.value) * parseFloat(price.get(0).innerHTML||0);
sum.text(value);
getTotal();
})
答案 0 :(得分:0)
你做完后
$('#total').text(total);
你可以做到
$("form input[name='amount']").val(total);
答案 1 :(得分:0)
$('[name="amount"]').keyup(function() {
total = parseFloat(0);
$('.price').each(function() {
total += parseFloat($(this).text());
});
$('#total').text(total);
});
答案 2 :(得分:-1)
你的意思是这样吗?
<table>
<thead>
<tr>
<th>VARIABLE</th>
<th>QTY</th>
<th>PRICE</th>
<th>SUM</th>
</tr>
</thead>
<tbody>
<tr>
<td>Millage</td>
<td><input class='qty' size='1'/></td>
<td class='price'>1.25</td>
<td class='sum'>0</td>
</tr>
<tr>
<td> Number of vans</td>
<td><input class='qty' size='1'/></td>
<td class='price'>2.10</td>
<td class='sum'>0</td>
</tr>
<tr>
<td colspan='2'>Total</td>
<td id='total'></td>
</tr>
</tbody>
</table>
<form action="">
<input id="amount" name="amount" value="0.00"><!-- add an id for amount -->
</form>
function getTotal(){
var total = 0;
$('.sum').each(function(){
total += parseFloat(this.innerHTML)
});
$('#total').text(total);
$('#amount').val(total); // set 'amount' value.
// $("form input[name='amount']").val(total); // If you want to target it by name, use this.
}
getTotal();
$('.qty').keyup(function(){
var parent = $(this).parents('tr');
var price = $('.price', parent);
var sum = $('.sum', parent);
var value = parseInt(this.value) * parseFloat(price.get(0).innerHTML||0);
sum.text(value);
getTotal();
})