Building an e-Commerce website with Node – Part 44 – Add interactivity to Plus and Minus buttons in Node.js

We have to add interactivity to our “+” and “-” buttons on the single product page. That means when the user clicks on the “+” button the quatity will increase by 1 and when the “-” button will be clicked the quantity will decrease by 1.

We do this in the custom.js file under the public/js folder. Open the file and type in the following code.

  $(document).on('click', '#plus', function(e) {
    e.preventDefault();
    var priceValue = parseFloat($('#priceValue').val());
    var quantity = parseInt($('#quantity').val());

    priceValue += parseFloat($('#priceHidden').val());
    quantity += 1;

    $('#quantity').val(quantity);
    $('#priceValue').val(priceValue.toFixed(2));
    $('#total').html(quantity);
  });


  $(document).on('click', '#minus', function(e) {
    e.preventDefault();
    var priceValue = parseFloat($('#priceValue').val());
    var quantity = parseInt($('#quantity').val());

    if (quantity == 1) {
      priceValue = $('#priceHidden').val();
      quantity = 1;
    } else {
      priceValue -= parseFloat($('#priceHidden').val());
      quantity -= 1;
    }

    $('#quantity').val(quantity);
    $('#priceValue').val(priceValue.toFixed(2));
    $('#total').html(quantity);
  });

First, on the “+” button, we apply an event-driven method. When you click the targeted button (which is the button with the id=”plus” something will happen.

The e.preventDefault(); prevents the page to be refreshed.
Next, we parce the value of the price and quantity so we can do some calculations later on.
Next we have the original price of the product (which will not change) (it is #priceHidden). When you click on the “+” button, the quantity will be increased by 1 (now, instead of 1 product you will have 2 products), and the #priceValue will be increased as well (2 products will have a price double than 1 product).

So, when you press “+” will increment both the quantity and the price.

The $('#quantity').val(quantity); posts everything to the server.
The $('#priceValue').val(priceValue.toFixed(2)); keeps the decimals (of the price) to 2.
The $('#total').html(quantity); shows the total quantity on the page.

For “-” is the same as it is for “+” but basically it is in reverse.

Take a look at the code below.

if (quantity == 1) {
    priceValue = $('#priceHidden').val();
    quantity = 1;
  } else {
    priceValue -= parseFloat($('#priceHidden').val());
    quantity -= 1;
  }

It prevents the quantity to go below zero (and the price as well). Without that code if you keep pressing the “-” button the quantity will go below zero and the price will be negative as well.

Leave a Reply