Skip to content
Advertisement

Increment and Decrement price value on Change

i’m trying to do an price counter synchronizing with increment and decrement buttons, but the price is not changing when i click one of the buttons (+/-) this is not working, how can i solve this issue? Thanks!!!

$('#plus').click(function add() {
    var $qtde = $("#quantity");
    var a = $qtde.val();
    
    a++;
    $("#minus").attr("disabled", !a);
    $qtde.val(a);
});
$("#minus").attr("disabled", !$("#quantity").val());

$('#minus').click(function minust() {
    var $qtde = $("#quantity");
    var b = $qtde.val();
    if (b >= 1) {
        b--;
        $qtde.val(b);
    }
    else {
        $("#minus").attr("disabled", true);
    }
});

/* On change */
$(document).ready(function()
{
    function updatePrice()
    {
        var price = parseFloat($("#quantity").val());
        var total = (price + 1) * 1.05;
        var total = total.toFixed(2);
        $("#total-price").val(total);
    }
    $(document).on("change, keyup, focus", "#quantity", updatePrice);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="minus" />
<input type="text" id="quantity" value="" name="quantity" />
<input type="button" value="+" id="plus" />
<br />
<input id="total-price" readonly="readonly" value=""/>

Advertisement

Answer

If you change your binding to update whenever there is a click on an input, you’ll get the behavior that you are expecting.

$('#plus').click(function add() {
  var $qtde = $("#quantity");
  var a = $qtde.val();

  a++;
  $("#minus").attr("disabled", !a);
  $qtde.val(a);
});
$("#minus").attr("disabled", !$("#quantity").val());

$('#minus').click(function minust() {
  var $qtde = $("#quantity");
  var b = $qtde.val();
  if (b >= 1) {
    b--;
    $qtde.val(b);
  } else {
    $("#minus").attr("disabled", true);
  }
});

/* On change */
$(document).ready(function() {
  function updatePrice() {
    var price = parseFloat($("#quantity").val());
    var total = (price + 1) * 1.05;
    var total = total.toFixed(2);
    $("#total-price").val(total);
  }
  // On the click of an input, update the price
  $(document).on("click", "input", updatePrice);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="minus" />
<input type="text" id="quantity" value="" name="quantity" />
<input type="button" value="+" id="plus" />
<br />
<input id="total-price" readonly="readonly" value="" />
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement