Building an e-Commerce website with Node – Part 43 – Add to cart button in Node.js

Now we need an “Add to cart” button for our application. The button has to be on the product page so we have to modify the product.ejs page. We also need to add product information to the cart through a few forms. Open product.ejs, it is under the views/main folder, and type the following code.

<form method="post">
        <div class="btn-group" role="group" aria-label="...">
          <input type="hidden" name="quantity" id="quantity" value="1"></input>
          <button type="button" id="minus" class="btn btn-default">-</button>
          <button type="button" id="total" class="btn btn-default">1</button>
          <button type="button" id="plus" class="btn btn-default">+</button>

        <div class="form-group">
          <input type="hidden" name="product_id" id="quantity" value="<%= product._id %>"></input>
          <input type="hidden" name="priceHidden" id="priceHidden" value="<%= product.price %>"></input>

          <input type="text" name="item" class="form-control" value="<%= %>"></input>
          <input type="text" name="priceValue" id="priceValue" class="form-control" value="<%= product.price %>"></input>

        <% if (user)  { %>
          <button type="submit" class="btn btn-primary btn-lg">Add to Cart</button>
        <% } else { %>
          <a href='/signup' class="btn btn-warning btn-lg">Signup to begin buying!</a>
        <% } %>

Now, go to http://localhost:3000, sign in, and click on one product. You are taken to that product page. You should see something like is shown below.

Add to cart button

As you can see, we have the “Add to Cart” button as well as three other rows. One row is the quantity the use wants to buy. The quantity can be increased or decreased (we will be add this feature later on). The second row is the name of the product, and the third row is the price. The price will be changed according to the quantity.

For example, in the picture above the price is 344. If the quantity is 2 then the price will be 688.

Leave a Reply