我无法在表td“ jumlah”上总计“总计”
<script>
$(document).on("change", ".jumlah", function() {
var sum = 0;
$(".jumlah").each(function(){
sum += +$(this).val();
});
$(".total").val(sum);
});
</script>
<input type="text" id="total" class="total" value="" />
我希望jumlah 的总输出是
答案 0 :(得分:0)
具有[contenteditable]
属性的元素将不具有[value]
属性,因为:
<div></div>
,<section></section>
,<spab></span>
等非交互,非无效,流和短语元素才能具有[contenteditable]
。<input>
,<textarea>
,<output>
等表单控件才能具有[value]
属性。因此,请使用.val()
而不是.text()
,因为文本是非格式控件的标记之间的内容。重要的变化是三元数:
如果这是输入,则获取其值,否则获取其文本
sum += $(this).is('input') ? +$(this).val() : +$(this).text();
次要更改是:
$('.totals').on("input", ".subtotal", function() {
let sum = 0;
$(".subtotal").each(function(){
sum += $(this).is('input') ? +$(this).val() : +$(this).text();
});
$(".total").val(sum);
});
:root {font:700 16px/1.2 Consolas}
input, output, data {display:inline-block;font:inherit;text-align:right;width:125px;}
output, data {width:50px}
data {outline:1px solid #aaa;padding:2px 17px 2px 0px;margin:1px 0px 1px 2px;width:110px}
<form class='totals'>
<table>
<tr><td><input class="subtotal" type='number' value='0'></td></tr>
<tr><td><input class="subtotal" type='number' value='0'></td></tr>
<tr><td><input class="subtotal" type='number' value='0'></td></tr>
<tr><td><data class="subtotal" contenteditable>0</data></td></tr>
<tr><td><data class="subtotal" contenteditable>0</data></td></tr>
<tr><td><data class="subtotal" contenteditable>0</data></td></tr>
<tr><td>Total: <output class="total">0</output></td></tr>
</table>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 1 :(得分:-1)
我创建了一个非常简单的示例,满足了您的需求,我认为您可以轻松地在代码中实现类似的内容。
$('.jumlah').on('input', function() {
let elementsToSum = $(document).find('.jumlah');
let sum = 0;
for (let ele of elementsToSum) {
// Parse the value of the <td> to integer
let eleIntValue = parseInt($(ele).html());
if (!isNaN(eleIntValue)) {
// Only add it to the sum if it is a number (not empty)
sum += eleIntValue;
}
}
// Change the value of <input> with the new calculated sum
$('#total').val(sum);
});
td {
width: 50px;
}
<table border="1">
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
<tr>
<td contenteditable="true" class="jumlah"></td>
</tr>
</table>
<br>
<input type="text" id="total" class="total" value="" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>