Rakhi Sharma
Rakhi Sharma

Reputation: 119

How to calculate price when increase and decrease quantity in JavaScript or jQuery?

I have a function to calculate price when user try to increase or decrease product quantity. When increasing quantity, price is calculated accurately. But when try to decrease quantity, then showing wrong result. How to calculate price when increasing or decreasing quantity of item using jQuery or JavaScript?

Below function is adding required data inside DIV into 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");
                }
            });
            
    }

Below two functions are to calculate total price when increase or decrease quantity. But decrease quantity function is not working properly. It is multiplying the quantity with new amount and hence price is increasing.

    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);
        }
    }

Any suggestions would be appreciable.

Upvotes: 0

Views: 1865

Answers (2)

Hammad Anwar
Hammad Anwar

Reputation: 415

use backticks with template literals in your productmodal html so you can get rid of extra +" concatenation and add span in price li ${baseprice} now you don't need to use replace function.

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");
            }
        });

    }

rest of your actions functions

// 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')
    }

Upvotes: 2

Triet Doan
Triet Doan

Reputation: 12085

I think both of the functions are wrong. When you write the new price to the #priceid again, you lose the base price because you overwrite it. There are 2 ways to fix this:

1. Store the base price somewhere else

In this case, use the #priceid to display the current price only.

Supposed the base price is 10.0, your code should look more or less like this:

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. Calculate the base price again in every action.

Although this solution is less efficient than the first one, it's still can be used if you can't or don't want to store your base price.

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);
}

Upvotes: 1

Related Questions