DEV Community

Cover image for Updating shopping cart
Saliou Tine
Saliou Tine

Posted on

Updating shopping cart

HI There guys
I just started project for someone and I stuck here in this section.
I am trying to add the contents of A&B element selected as shown on the picture, to cart once I click [ADD TO CART BUTTON 👉(C)] to be added to the VALUE (9.50 + 0.10 = 9.60).Please help me.!!!
Thank you very much guys.
Kind Regards Sal 🙏🤦‍♂️😍

So this is my code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>Shopping Cart Course Discoveryvip.com</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css"
      integrity="sha384-AysaV+vQoT3kOAXZkl02PThvDr8HYKPZhNT5h/CXfBThSRXQ6jW5DO2ekP5ViFdi"
      crossorigin="anonymous"
    />
    <style>
      #output {
        clear: both;
      }

      #checkoutdiv {
        display: none;
      }
s
      .footer {
        background-color: darkgrey;
        color: white;
      }
      .htop{width:70%; background-color: rgb(231, 180, 113); margin: auto;}
.text-muted {
   color: #2a4d68!important;
}
      .memories{width: 80%; margin: 30px;}
.card-flex{display: flex;  width: 70%; margin:60px auto ;}

.container-ctn{position: relative; bottom: 0; background-color: rgb(68, 155, 94); height: 200px;}
      #formId{width:100%; background-color: rgb(240, 238, 241);}
    </style>
  </head>

  <body>
    <header class="header">
      <div class="htop">
        <div id="checkoutdiv " class="container">
          <div class="row">
            <div class="col-md-6 text-xs-right">
              (<span class="items text-muted"></span> <small>items</small>)
              <span class="total"></span>
            </div>
            <div class="col-md-6 text-xs-right">
              <span
                class="btn btn-success"
                data-toggle="modal"
                data-target="#cart"
                >Open Shopping Cart</span
              ><a href="checkitout.html" class="btn btn-primary"
                >Proceed to checkout</a
              >
            </div>
          </div>
        </div>
      </div>


        </header>




        <div class="roller">
             <div class="card-flex">
               <div class="memories"> <img src="fj1.jpeg" class="img-fluid" /></div>



               <form class="myform" id="formId" method="dialog"> 
               <h3 class="card-title"> Ribeye Steaks</h3>
               <p>
The timeless classic and historically the most popular of the top 4 steaks. With such fantastic
 flavour, you can never be disappointed with this choice</p>
                <h6 class="card-subtitle text-muted">28 days Ribeye Steaks Only at £7.00</h6>
               <div class="optwheight">wheight-options</div>
               <select id="mySelect" onchange="myFunction()">
               <option value="0" selected>select
               <option value="£9.50" >226.79g
               <option value="£8.20">220g
               <option value="£9.50">280g
                <option value="£8.20">220g

                </select>
                <p data-price="" 
                data-id="1"  class="productItem" id="demo"></p>


              <a href="#" 
               class="card-link productItem btn btn-primary" data-name="Beef"
               data-s="Ribeye Steaks"  data-price="" 
                data-id="1">Add to Cart</a> 
               <div><input id="res" type="reset" /></div>

              </div>

             </form>



      </div>




    <!-- Modals -->
    <div class="modal fade" id="cart" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Shopping Cart</h4>
          </div>
          <div class="modal-body">
            <table class="table table-hover">
              <thead class="thead-inverse">
                <tr>
                  <th>Qty</th>
                  <th>Item Name</th>
                  <th>Weight</th>
                  <th>Cost</th>
                  <th class="text-xs-right">Subtotal</th>
                  <th>Remove</th>
                </tr>
              </thead>
              <tbody id="output"></tbody>
            </table>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-warning" data-dismiss="modal">
              Continue Shopping</button>
            <a href="checkitout.html" ><button class="btn btn-primary">Proceed to checkout</button>
              </a
            >
          </div>
        </div>
      </div>
    </div>
<footer class="footer">
      <div class="container-ctn">
        <p class="text-xs-center">© Copyright info blah blah</p>
      </div>
    </footer>
    <script>
        function myFunction() {
          var x = document.getElementById("mySelect").value;
          document.getElementById("demo").innerHTML = " " + x;
        }
      </script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js"
      integrity="sha384-XTs3FgkjiBgo8qjEjBk0tGmf3wPrWtA6coPfQDfFEY8AnYJwjalXCiosYRBIBZX8"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"
      integrity="sha384-BLiI7JTZm+JWlgKa0M0kGRpJbF2J8q+qreVrKBC47e3K6BW78kGLrCkeRX6I9RoK"
      crossorigin="anonymous"
    ></script>
    <script>
// $(".productItem").click(function (e)
//  { e.preventDefault();
//    var iteminfo = $(this.dataset)[0]; 
//    let selectedItem = $('#mySelect option:selected')

   //add. selected option selector iteminfo.qty = 1; 
  //  iteminfo.price = selectedItem.val().replace('£','') //add. 
   //value of selected option. 
   //You'd better find a better way to use the formatMoney function with the numeric calculation instead of using .replace() iteminfo.weight = selectedItem.text() //add. text of selected option var itemincart = false; $.each(shopcart, function (index, value) { //console.log(index + ' ' + value.id); if (value.id == iteminfo.id) { value.qty = parseInt(value.qty) + parseInt(iteminfo.qty); itemincart = true; } }); if (!itemincart) { shopcart.push(iteminfo); } sessionStorage["sca"] = JSON.stringify(shopcart); outputCart(); /// });


// let addItem = $('#demo option:selected')
//  iteminfo.price = addItem.val().replace('£','')

      var shopcart = [];
      $(document).ready(function () {
        outputCart();
        $(".productItem").click(function (e) {
          e.preventDefault();
          var iteminfo = $(this.dataset)[0];
          let selectedItem = $('#mySelect option:selected') //add. selected option selector
          let addItem = $('#demo option:selected')

          iteminfo.qty = 1;
          iteminfo.price = selectedItem.val().replace('£','') //add. value of selected option.
            // iteminfo.price = addItem.val().replace('£','')
//You'd better find a better way to use the formatMoney function with the numeric calculation instead of using .replace()
          iteminfo.weight = selectedItem.text() //add. text of selected option
          var itemincart = false;
          $.each(shopcart, function (index, value) {
            //console.log(index + '  ' + value.id);
            if (value.id == iteminfo.id) {
              value.qty = parseInt(value.qty) + parseInt(iteminfo.qty);
              itemincart = true;
            }
          });
          if (!itemincart) {
            shopcart.push(iteminfo);
          }
          sessionStorage["sca"] = JSON.stringify(shopcart);
          outputCart();
          ///
        });

        function outputCart() {
          if (sessionStorage["sca"] != null) {
            shopcart = JSON.parse(sessionStorage["sca"].toString());
            console.log(sessionStorage["sca"]);
            $("#checkoutdiv").show();
          }
          var holderHTML = "";
          var total = 0;
          var itemCnt = 0;
          $.each(shopcart, function (index, value) {
            console.log(value);


            var stotal = value.qty * value.price;
            total += stotal;
            itemCnt += parseInt(value.qty);
            holderHTML +="<tr><td>" +value.qty +"</td><td>#" + value.id + " " +value.name +
              "(" +
              value.s +
              ")</td><td> " + //add
              value.weight + //add
              "</td><td> " +
              formatMoney(value.price) +
              ' </td><td class="text-xs-right"> ' +
              formatMoney(stotal) +
              '</td><td><span class="remove-item btn btn-danger">x</span></td></tr>';

          });



          holderHTML +=
            '<tr><td colspan="3" class="text-xs-right">Total</td><td class="text-xs-right">' +
            formatMoney(total) +
            "</td></tr>";
          $("#output").html(holderHTML);
          $(".total").html(formatMoney(total));
          $(".items").html(itemCnt);
        }

        function formatMoney(n) {
          return "£" + (n / 100).toFixed(2);
        }
        $("#output").on("click", ".remove-item", function () {
          var itemInfo = $(this.dataset)[0];
          var itemToDelete = $(".remove-item").index(this);
          shopcart.splice(itemToDelete, 1);
          sessionStorage["sca"] = JSON.stringify(shopcart);
          outputCart();
        });









      });
    </script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (1)

Collapse
 
ale_zampa profile image
Ale Zampa

Just see on stackoverflow