我尝试使用jquery计算表上的总数,但是当运行总计时没有出现。所以当我输入输入值,总自动求和,错误时,我想显示总的实时数?
HTML
<table class="table table-condensed">
<thead>
<tr>
<td class="text-left"><strong>Product</strong></td>
<td class="text-center"><strong>Value</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_a" name="producta" value="12.000"></td>
</tr>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_b" name="producta" value="19.000"></td>
</tr>
<tr>
<td>Microwave</td>
<td><input type="text" id="product_c" name="producta" value="15.000"></td>
</tr>
<tr>
<td class="thick-line"><strong>Total</strong></td>
<td class="thick-line"><input type="text" id="total" name="total" /></td>
</tr>
</tbody>
</table>
JS
jQuery(document).ready(function(){
var total = ($('#product_a').val() + $('#product_b').val() + $('#product_c').val()) ;
$('#total').val(total);
});
答案 0 :(得分:1)
您可以尝试以下代码....
jQuery(document).ready(function(){
$("input").on("change",updateTotal); // this will total on change input.
updateTotal(); //this will total on start..
});
function updateTotal()
{
var total = ($('#product_a').val()*1 + $('#product_b').val()*1 + $('#product_c').val()*1) ;
//By multiplying 1 to any string format number it will convert to number datatype.
//var total = (Number($('#product_a').val()) + Number($('#product_b').val()) + Number($('#product_c').val()));
//You can also uncomment above line to get your desire output.
$('#total').val(total);
}
答案 1 :(得分:1)
你做错了。 val()
返回input[type=text]
上的字符串,目前您只是连接字符串值。
我想在输入输入值
时显示实时总数
然后,您需要在键入时更改输入时添加侦听器。这可以通过keyup
事件来完成。
<强> E.g。强>
$(function() {
var $aProduct = $('#product_a'),
$bProduct = $('#product_b'),
$cProduct = $('#product_c'),
$total = $('#total'),
runTotal = function() {
var a = parseInt($aProduct.val()),
b = parseInt($bProduct.val()),
c = parseInt($cProduct.val());
$total.val(a + b + c);
};
$('.inputVal').on('keyup', runTotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed">
<thead>
<tr>
<td class="text-left"><strong>Product</strong>
</td>
<td class="text-center"><strong>Value</strong>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_a" name="producta" class="inputVal" value="12.000">
</td>
</tr>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_b" name="productb" class="inputVal" value="19.000">
</td>
</tr>
<tr>
<td>Microwave</td>
<td>
<input type="text" id="product_c" name="productc" class="inputVal" value="15.000">
</td>
</tr>
<tr>
<td class="thick-line"><strong>Total</strong>
</td>
<td class="thick-line">
<input type="text" id="total" name="total" />
</td>
</tr>
</tbody>
</table>