我正在创建POS应用程序,当我从SONY之类的数据库中的自动完成产品中选择产品时,默认情况下,其数量为1,当再次选择此产品SONY时,我希望在下表中仅更新数量,而在相同代码下不添加新行更新数量请指导我。
function addProduct() {
var procode_1 = $('#procode_1').val();
var product = {
procode: $('#procode_1').val(),
prname: $('#proname_1').val(),
qty: $('#qty_1').val(),
price: $('#price_1').val(),
tot_cost: $('#totcost_1').val(),
};
addRow(product);
$("#proname_1").val(' ');
}
function addRow(product) {
var qty = $('#qty').val();
if ($('#procode_1').val().length == 0) {
$.alert({
title: "Error",
content: "Please Enter Stock Code",
type: "red",
autoClose: 'ok|2000'
});
} else if (!$('#currentstock_1').val() < qty) {
$.alert({
title: "Error",
content: "Product is not enough!",
type: "red",
autoClose: 'ok|2000'
});
} else {
sr++;
$('#productlist').show();
var $tableB = $('#productlist tbody');
var $row = $(
"<tr style='text-align: center;'>" +
"<td width='5%' style='display: none;'>" + sr + "</td>" +
"<td width='15%'>" + product.procode + "</td>" +
"<td width='20%'>" + product.prname + "</td>" +
"<td width='20%' >" + product.qty + "</td>" +
"<td width='5%' >" + product.price + "</td>" +
"<td class='totalLinePrice'>" + product.tot_cost + "</td>" +
"</tr>"
);
$row.data("lineitem", product.sr);
$row.data("procode", product.procode);
$row.data("prname", product.prname);
$row.data("qty", product.qty);
$row.data("price", product.price);
$row.data("tot_cost", product.tot_cost);
$tableB.append($row);
total += Number(product.tot_cost);
$('#sub_total').val(total);
$('#total_invoice').val(total);
}
}
答案 0 :(得分:0)
我简化了您的代码,以使所有内容更具可读性。评论应该足以理解其工作原理。 希望对您有帮助。
$('#add').click(function() {
var c = $('#code').val();
var q = $('#qty').val();
// Important here is the new class='qty'
var $row = $(
"<tr style='text-align: center;'>" +
" <td width='80%' style='border-right:solid 1px black;' >" + c + "</td>" +
" <td class='qty' width='20%'>" + q + "</td>" +
"</tr>"
);
// Check if code exists
var exists = false;
$('#productlist tbody tr').each(function() {
// If exists a product with the same productCode...
if ($(this).data('procode') == c) {
// Flag exists
exists = true;
// Update old quantity internal data
$(this).data('qty', parseInt(q) + parseInt($(this).data('qty')));
// Update table with new value
$('.qty', this).html($(this).data('qty'));
}
});
// If not, we create a new row
if (!exists) {
$row.data("procode", c);
$row.data("qty", q);
$('#productlist tbody').append($row);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="display:inline-block; width: 50px">Code:</div> <input id="code" type="text" />
<br/><br/>
<div style="display:inline-block; width: 50px">Qty:</div> <input id="qty" type="text" />
<br/><br/>
<div style="display:inline-block; width: 50px"></div> <button id="add">Add</button>
<br/><br/><br/>
<table id="productlist" style="width:300px; border:solid 1px black;">
<tbody>
<tr>
<th width='80%' style='border-right:solid 1px black;'>Product Code</th>
<th width='20%'>Qty</th>
</tr>
</tbody>
</table>