使用Javascript:计算附加值
我有这张增加了服务的表。我试图输入evry的数量,并显示在右侧的键盘上的总数。
我只能得到第一行而不是下一行。
这里是我的代码
$(document).on('keyup',function(){
var pri = $('#price_display').val();
var q = $('#qty_display').val();
var tots = pri*q;
$('#sub_display').val(tots);
});
每一行通过追加 price_display增加持有价格值 qty_display保存输入值 sub_dispplay保持输出值
我我愿意赌每一行的每列都有相同的ID(例如id=price_display
)。按照定义,ID必须在每个页面上都是唯一的,所以jQuery总是会找到每个页面的第一个实例(即第一行)。
也许最简单的方法是在每个字段上附加一个行号, price_display_1
,qty_display_1
,sub_quantity_1
等 - 这样jQuery可以查找每个字段的正确实例。
查看下面的例子 - 虽然说了这么多,但看起来好像您正在使用类似Angular Material的样式来设计页面风格,所以您可能需要花时间在AngularJS中调查数据绑定以节省麻烦。
// source data for table (array holds a JavaScript object per row)
var tableData = [{
serviceCode: 'xbed',
serviceName: 'xbed',
price: 500,
quantity: 1
},
{
serviceCode: 'xpil',
serviceName: 'xpil',
price: 200,
quantity: 2
}
];
// find the table body
var $tableBody = $("#myTable").children("tbody");
// for each row of data, generate a table row
tableData.forEach(function(row, index) {
var rowIndex = index + 1;
$tableBody.append("<tr>" +
"<td><input type='text' id='service_code_" + rowIndex + "' value='" + row.serviceCode + "' /></td>" +
"<td><input type='text' id='service_name_" + rowIndex + "' value='" + row.serviceName + "' /></td>" +
"<td><input type='text' class='price' id='price_display_" + rowIndex + "' value='" + row.price + "' /></td>" +
"<td><input type='text' class='qty' id='qty_display_" + rowIndex + "' value='" + row.quantity + "' /></td>" +
"<td><input type='text' class='total' id='sub_display_" + rowIndex + "' value='" + row.price * row.quantity + "' /></td>" +
"</tr>");
});
// wire up keyboard handlers
$(".price, .qty").on("keyup", function(evt) {
var $row = $(evt.target).closest("tr"),
price = $row.find(".price").first().val(),
qty = $row.find(".qty").first().val(),
$total = $row.find(".total").first();
$total.val(price * qty);
});
table {
font-family: 'Arial', sans-serif;
}
input {
width: 8em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>Service code</th>
<th>Service name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
改变ID类和尝试代码:
$(document).on('keyup', '.qty_display, .price_display', function(){
var row = $(this).parent('tr');
var pri = row.find('.qty_display').val();
var q = row.find('.price_display').val();
var tots = pri*q;
row.find('.sub_display').val(tots);
});
这样一来,你会改变只需要用正确的值的行。
尝试记录“tots”变量的值,是否会出现?
如果是
**THEN**
make sure must have unique "#sub_display" id to display the value else it only appears on the first raw
如果NO
**THEN**
try to log the second raw object eg:-console.log(this)
我不熟悉日志,但不好意思看它。谢谢 – PEENGEE
我的意思是console.log(“value here”,变量) –
的ID必须为**行独特的** – Andreas
使用ID,但是对于列使用类 –
如果我使用类。每个输出都是相同的 – PEENGEE