【发布时间】:2019-08-07 17:59:25
【问题描述】:
我正在制作一个简单的结帐表单,用户只需在表单中输入产品代码、产品类型和他们想要购买的产品数量,然后使用 jQuery 根据他们想要购买的数量并在总字段上显示。
<div id="startcart">
<div id="cart0">
<div class="row">
<div class="col-25">
<input type="text" name="kodeproduk[]" value="" placeholder="Kode Produk" class="form-control">
</div>
<div class="col-25">
<input type="text" name="tipeproduk[]" value="" placeholder="Tipe Handphone" class="form-control">
</div>
<div class="col-25">
<input type="number" name="jumlah[]" placeholder="0" class="form-control jumlah" min="0"/>
</div>
<div class="col-25">
<input type="number" name="total[]" value="" placeholder="Total" class="form-control total" readonly>
</div>
</div>
</div>
<div id="cart1"></div>
</div>
问题是,现在总价仅显示在作为父字段的第一个字段上,每当我尝试动态添加更多字段并更改数量时,总价值仅计算基于第一个字段的值字段,但总数计算完美
我试图映射数组并且 qty 数组工作正常,但不适用于总数组 下面是我使用的 jQuery 脚本
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
b=i-1;
var html = $(this).nextAll("#cart0").html();
//console.log(html);
//console.log(b);
$('#cart'+i).html($('#cart'+b).html()).find('#cart'+b).html(i+1);
$('#startcart').append('<div id="cart'+(i+1)+'"></div>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#cart"+(i-1)).html('');
i--;
}
calc();
});
$('#startcart').on("keyup change", ".jumlah", function(){
calc();
});
$('#tax').on('keyup change',function(){
calc_total();
});
});
function calc()
{
/*$("div#startcart").each(function() {
//console.log($(this));
});*/
$('#startcart').each(function(i, element) {
var html = $(this).html();
console.log(html);
var jumlah = $(".jumlah").map(function(){ return this.value}).get();
console.log(jumlah);
var total = $(".total").map(function(){ return this.value}).get();
console.log(total);
if(html!='')
{
var qty = $(".jumlah").val();
//var qty = $(item).val();
console.log("jumlah kuantiti "+qty);
var price = 25000;
//var totalprice = qty*price;
//console.log(totalprice);
$(".total").val(qty*price);
calc_total();
}
});
}
function calc_total()
{
total=0;
jumlah=0;
$('.total').each(function() {
total += parseInt($(this).val());
});
$('.jumlah').each(function() {
jumlah += parseInt($(this).val());
console.log(jumlah);
});
var GrandTo = document.getElementById('GrandTotal');
var GrandPro = document.getElementById('JumlahOrder');
GrandTo.innerHTML = '<b>Rp '+total.toFixed(2)+'</b>';
JumlahOrder.innerHTML = '<b> '+jumlah+'</b>';
}
如果你需要复现问题,可以通过访问https://jsfiddle.net/boiler/7Lacn2mx/1来实现
【问题讨论】:
-
jQuery 没有看到 dom 变化可能是原因。
-
固定小提琴:jsfiddle.net/c72ghupv
标签: jquery