javascript - 如何在 JQuery 中获取总数
问题描述
我使用查询创建了简单的库存控制表单。单击添加按钮后,它由(产品名称,价格)组成,它将成功附加到表格行上。我的问题是在最后加上一个价格后我无法计算最终的总数。我不知道该怎么做。到目前为止我尝试了什么。我写在下面。任何人都可以通过代码并给出好的解决方案。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add / Remove Table Rows</title>
<style type="text/css">
table{
width: 100%;
margin: 20px 0;
border-collapse: collapse;
}
table, th, td{
border: 1px solid #cdcdcd;
}
table th, table td{
padding: 5px;
text-align: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".add-row").click(function(){
tot = 0;
var ProductName = $("#ProductName").val();
var Price = $("#Price").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + ProductName + "</td><td>" + Price + "</td></tr>";
$("table tbody").append(markup);
tot += parseFloat(email);
});
// Find and remove selected table rows
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text" id="ProductName" placeholder="ProductName">
<input type="text" id="Price" placeholder="Price">
<input type="button" class="add-row" value="Add Row">
<label>Amount </label>
<input type="text" size="30" height="20" id="tot" placeholder="Total">
</form>
<table>
<thead>
<tr>
<th>Select</th>
<th>ProductName</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="button" class="delete-row">Delete Row</button>
</body>
</html>
解决方案
<body>
<form>
<input type="text" id="ProductName" placeholder="ProductName">
<input type="text" id="Price" placeholder="Price">
<input type="button" class="add-row" value="Add Row">
<label>Amount </label>
<input type="text" size="30" height="20" id="tot" placeholder="Total" readonly>
</form>
</body>
<script>
$(".add-row").click(function(){
var ProductName = $("#ProductName").val();
var Price = $("#Price").val();
var tot = $("#tot").val();
if(tot == ""){
tot = 0;
}
tot = parseFloat(tot) + parseFloat(Price);
$("#tot").val(tot);
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + ProductName + "</td><td>" + Price + "</td></tr>";
$("table tbody").append(markup);
});
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
var total = parseFloat($("#tot").val());
var newtotal = total - parseFloat($(this).data("price"));
$("#tot").val(newtotal);
$(this).parents("tr").remove();
}
});
});
</script>
推荐阅读
- c++ - 如何使用模板函数进行隐式转换
- ruby-on-rails - 如何在 do 循环中发布请求 API
- python - 为什么比较两个数据帧时会得到不同的结果?
- r - dplyr 中的管道 (|) 如何在 Shiny 和数据表的上下文中工作?
- javascript - 当我尝试将多个点击侦听器添加到标记 django 时,initMap 不是一个函数
- javafx - 条形图无法正确显示
- r - 如何根据 R 中的另一个数据框更改数据框中的值?
- android - 对话框全屏布局问题
- php - Laravel:更新身份验证用户数据然后显示视图
- javascript - 调用异步函数的客户端代码是否需要使用等待?