如何用JavaScript或jQuery计算增减数量时的价格?



当用户试图增加或减少产品数量时,我有一个函数来计算价格。增加数量时,价格计算准确。但当试图减少数量时,就会出现错误的结果。如何计算价格时增加或减少数量的项目使用jQuery或JavaScript?

下面的函数是在DIV中添加所需的数据到modal.

function getmodal(mappedcityid){
            var url = "api/viewproductbyid";
            $.post(url, {
                mappedcityid : mappedcityid,
            }, function(data, status) {
                if (data.status == "OK") {
                    if (data.statusCode == 1) {
                        var productdata = data.response;
                        var baseprice = productdata.baseprice;
                        var productname = productdata.product.prductname;
                        document.getElementById('productmodal').innerHTML = "<div class="product-details-content quickview-content">"
                            +"<h2>"+productname+"</h2>"
                            +"<div class="pricing-meta">"
                                +"<ul>"
                                    +"<li class="old-price not-cut" id="priceid">&#8377;&nbsp;"+baseprice+"</li>"
                                +"</ul>"
                            +"</div>"
                            +"<p>"+description+"</p>"
                            +"<div class="pro-details-quality">"
                                +"<div class="cart-plus-minus">"
                                    +"<div class="dec qtybutton" onclick="decbtn();">-</div>"
                                    +"<input class="cart-plus-minus-box" type="text" name="qtybutton" id="quantity" value="1" onkeyup="countprice();"/>"
                                    +"<div class="inc qtybutton" onclick="incbtn();">+</div>"
                                +"</div>"
                            +"</div>"
                        +"</div>"; 
                    } else {
                        var error = data.responseMessage;
                        swal(error, "", "error");
                    }
                } else {
                    var error = data.responseMessage;
                    swal(error, "", "error");
                }
            });
            
    }

下面两个函数是在增加或减少数量时计算总价。但减量功能没有正常工作。它将数量乘以新的数量,因此价格在上涨。

    function decbtn(){
        var amount = "";
        var price = $("#priceid").text();
        var oldprice = price.replace(/[^x00-x7F]/g, "");
        var val = $("#quantity").val();
        if(val <= 1){
            val = 1;
        }else{
            val = val-1;
        }
        $("#quantity").val(val);
        if(null != oldprice || oldprice != ""){
            amount = parseFloat(oldprice)*parseFloat(val);
            $("#priceid").html('&#8377;&nbsp;'+amount);
        }
    }
    function incbtn(){
        var amount = "";
        var price = $("#priceid").text();
        var oldprice = price.replace(/[^x00-x7F]/g, "");
        var val = $("#quantity").val();
        val = parseInt(val)+1;
        $("#quantity").val(val);
        if(null != oldprice || oldprice != ""){
            amount = parseFloat(oldprice)*parseFloat(val);
            $("#priceid").html('&#8377;&nbsp;'+amount);
        }
    }

任何建议都将是宝贵的。

在你的productmodal HTML中使用反引号作为模板文字,这样你就可以去掉额外的+"在price li ${baseprice}中连接和添加span,现在你不需要使用replace函数了。

function getmodal(mappedcityid) {
        var url = "api/viewproductbyid";
        $.post(url, {
            mappedcityid: mappedcityid,
        }, function(data, status) {
            if (data.status == "OK") {
                if (data.statusCode == 1) {
                    var productdata = data.response;
                    var baseprice = productdata.baseprice;
                    var productname = productdata.product.prductname;
                    document.getElementById('productmodal').innerHTML = `
                    <div class="product-details-content quickview-content">
                        <h2>${productname}</h2>
                        <div class="pricing-meta">
                            <ul>
                                <li class="old-price not-cut">&#8377;&nbsp;
                                    <span id="priceid">${baseprice}</span>
                                </li>
                            </ul>
                        </div>
                        <p>description</p>
                        <div class="pro-details-quality">
                            <div class="cart-plus-minus">
                                <div class="dec qtybutton" onclick="decbtn();">-</div>
                                <input class="cart-plus-minus-box" type="text" name="qtybutton" id="quantity" value="1" onkeyup="countprice();"/>
                                <div class="inc qtybutton" onclick="incbtn();">+</div>
                            </div>
                        </div>
                    </div>
                    `;
                } else {
                    var error = data.responseMessage;
                    swal(error, "", "error");
                }
            } else {
                var error = data.responseMessage;
                swal(error, "", "error");
            }
        });
    }

其余的actions函数

// calculateTotal function
    function calculateTotal(qty, type) {
        
        let productPrice = parseInt($('#priceid').html());
        if (type == 'decrement') {
            if (qty <= 1) {
                qty = 1;
            } else {
                qty = qty - 1;
            }
        }
        let totalProductPrice = productPrice * qty;
        $('#priceid').html(totalProductPrice);
    }
    // function to handle decrement button 
    function decbtn() {
        let val = $("#quantity").val();
        if (val <= 1) {
            val = 1;
        } else {
            val = val - 1;
        }
        $("#quantity").val(val);
        // call calculateTotal function with two params first one is qty and second one is action type
        calculateTotal(val,'decrement')
    }
    // function to handle increment button 
    function incbtn() {
        let val = $("#quantity").val();
        val = parseInt(val) + 1;
        $("#quantity").val(val);
        // call calculateTotal function with two params first one is qty and second one is action type
        calculateTotal(val,'increment')
    }

我认为这两个函数都是错误的。当你再次写新价格给#priceid时,你失去了基础价格,因为你重写了它。有两种方法可以解决这个问题:

1。将基本价格存储在其他地方

在本例中,使用#priceid仅显示当前价格。

假设基本价格是10.0,你的代码应该看起来或多或少像这样:

function decbtn() {
  const basePrice = 10.0;
  let val = $("#quantity").val();
  if (val <= 1) {
    val = 1;
  } else {
    val = val - 1;
  }
  $("#quantity").val(val);
  const currentPrice = basePrice * val;
  $("#priceid").html('&#8377;&nbsp;' + currentPrice);
}
function incbtn() {
  const basePrice = 10.0;
  let val = $("#quantity").val();
  val = parseInt(val) + 1;
  $("#quantity").val(val);
  const currentPrice = basePrice * val;
  $("#priceid").html('&#8377;&nbsp;' + currentPrice);
}

2。在每个动作中再次计算基础价格。

虽然这个解决方案不如第一个有效,但如果你不能或不想存储你的基本价格,它仍然可以使用。

function decbtn() {
  // Get the current price
  let currentPrice = $("#priceid").text().replace(/[^x00-x7F]/g, "");
  currentPrice = parseFloat(currentPrice);
  // Get the current quantity
  let val = $("#quantity").val();
  val = parseInt(val);
  // Calculate the base price
  const basePrice = currentPrice / val;
  // Update the new quantity
  if (val <= 1) {
    val = 1;
  } else {
    val = val - 1;
  }
  $("#quantity").val(val);
  // Calculate the new price
  const newPrice = basePrice * val;
  $("#priceid").html('&#8377;&nbsp;' + newPrice);
}
function incbtn() {
  // Get the current price
  let currentPrice = $("#priceid").text().replace(/[^x00-x7F]/g, "");
  currentPrice = parseFloat(currentPrice);
  // Get the current quantity
  let val = $("#quantity").val();
  val = parseInt(val);
  // Calculate the base price
  const basePrice = currentPrice / val;
  // Update the new quantity
  val = parseInt(val) + 1;
  $("#quantity").val(val);
  // Calculate the new price
  const newPrice = basePrice * val;
  $("#priceid").html('&#8377;&nbsp;' + newPrice);
}

最新更新