Fahad Almehaini
Fahad Almehaini

Reputation: 233

how to update the price if quantity changed in cart

I am making the Review Cart & Checkout form. IF user want to change the quantity I want that if quantity is changed the price of it will be changed automatically.

Please help to adjust the code in the same JS of plus minus or separate.

Image is below of Review Cart & Checkout: enter image description here

JS for Plus & Minus:

<script type="text/javascript">
function subtractQty(){
    if(document.getElementById("number").value - 1 < 0)
        return;
    else
    document.getElementById("number").value--;
    }
</script>

HTML/PHP for plus minus:

<div class="quantity">
<input style="font-size:21px;" type="button" value="-" onclick='javascript: subtractQty();' class="">
<input id="number" type="number" value="<?php echo $qtyT; ?>" class="qty" name="picpac">
<input style="font-size:21px;" type="button" value="+"  onclick='javascript: document.getElementById("number").value++;'  class="plus">
</div>

Upvotes: 0

Views: 6824

Answers (1)

dcalap
dcalap

Reputation: 1072

You can follow two different strategies:

  • Invoke the server with an Ajax call, pass the quantity as parameter, calculate the total amount and return it.
  • Do all the operations in the front-end with jQuery and finally, pass the calculated value to store it.

In this link I have coded a quick example for the second one with your provided HTML. I just added a div for the calculated value

<div id="product1_total_price">0</div>

An input hidden for the product base price

<input type="hidden" id="product1_base_price" value="10">

And this jQuery code that do the magic:

$(document).ready(function() {

$(".operator").on('click',function() {
  $("#product1_total_price").text($("#product1_base_price").val()*$("#number").val());
 });
});

Hope it helps.

EDITED:

I add a (and update the JSFiddle link) suppossed Ajax call with jQuery, to update the DB on every quantity change:

$.ajax({
        type: "GET",
        data: {
            idProduct: yourProductId,
            quantity: $("#number").val(),
            totalPrice: calculatedValue
        },
        url: "your-script.php",
        success: function(json_response) {

          if(json_response.result != 'SUCCESS') {
              // Whatever
          } else {
              alert("Updated in DB");
          });
    })

Upvotes: 1

Related Questions