$(document).ready(function() {
$(':checkbox').change(function() {
$('input:checkbox:checked').filter(function() {
var sum = 0;
var Something = parseFloat($(this).closest('tr').find('td:eq(2)').text()) + sum;
var value = Something;
alert(Something);
$('#total').html(value);
});
});
});
<table class="table table-bordered" id="echotable">
<tr>
<th class="field-label col-xs-1 primary">ID</th>
<th class="field-label col-xs-5 primary">Name Of Service</th>
<th class="field-label col-xs-3 primary">Price</th>
<th class="field-label col-xs-3 primary">Total</th>
</tr>
<?php foreach($echo_details as $post){?>
<tr class="active" id="myrow">
<td class="field-label col-xs-1 primary"><?php echo $post->echo_id;?></td>
<td class="field-label col-xs-5 primary"><?php echo $post->echo_scan;?></td>
<td class="field-label col-xs-3 primary" id="price"><?php echo $post->price;?></td>
<td class="field-label col-xs-3 primary"><input type="checkbox" id="myCheckbox" /></td>
</tr>
<?php }?>
<tr>
<td colspan="3" class="total"><strong>TOTAL</strong></td>
<td id="total"></td>
</tr>
我正在动态获取数据库中的值。当用户选择多个复选框时,我将获得所有价格值。现在我需要添加所有价格值并需要显示总成本。我怎么能这样做?
答案 0 :(得分:2)
你的逻辑不太正确。您需要使用each()
循环选中复选框,而不是filter()
。您还需要在循环外定义sum
并在每次迭代中添加html()
,然后在循环结束时设置'total'td
的{{1}}。最后请注意,您在class
个元素上设置了td
,而不是id
,因此您应该使用.total
而不是#total
来选择它。试试这个:
$(':checkbox').change(function() {
var sum = 0;
$('input:checkbox:checked').each(function() {
sum += parseFloat($(this).closest('tr').find('td:eq(2)').text());
});
$('.total').html(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>ID</th>
<th>Name Of Service</th>
<th>Price</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td>Echo</td>
<td>1000</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td>2</td>
<td>Fetal Echo</td>
<td>1500</td>
<td><input type="checkbox" /></td>
</tr>
<tr>
<td colspan="3">TOTAL</td>
<td class="total">0</td>
</tr>
</table>