js implements a simple shopping cart module

js implements a simple shopping cart module

This article example shares the specific code of js to implement a simple shopping cart module for your reference. The specific content is as follows

Key Features

  • Input box regular judgment, two-digit decimal, can start with 0
  • If the product names are the same, the quantity will be automatically increased by 1. If the names are the same but the prices are different, the latest price will prevail (there is a bug and multiple products cannot be operated. The program is confusing and will be modified later)
  • Select a product, or add or reduce the quantity, and the price and quantity in the lower right corner will be automatically updated.
  • The settled goods will disappear automatically

Source code:

1.html

<body>
      <div id="head" align="center">
        <form>
          <span class="font1">Name:</span><input type="text" id="name">
          <span class="font1">Unit price:</span><input type="text" id="price">
          <input id="add1" type="button" value="Add">
          <input id="pay1" type="button" value="Checkout">
          <input id="set1" type="reset" value="Reset">
        </form>
      </div>
      <div>
        <table border="1" id="t" >
          <thead>
          <tr align="center">
            <td><input type="checkbox" style='cursor: pointer'></td>
            <td>Product Name</td>
            <td>Price</td>
            <td>Quantity</td>
            <td>Operation</td>
          </tr>
          </thead>
          <tbody>

          </tbody>
        </table>
      </div>
      <div align="right" id="b">
        <span>Total price:</span>
        <span id="Total" style="color: red">0</span>&nbsp;
        <span>Quantity of product:</span>
        <span id="TotalNum" style="color: red">0</span>
      </div>
</body>

2.css

 <style>
        body{
          background-color: coral;
        }
        #head{
          margin:30px auto 10px auto;
        }
        #name,#price{
          background-color: aquamarine;
        }
        #add1,#pay1,#set1{
          color: red;
          font-weight: bold;
          background-color: gold;
          cursor: pointer;
        }
        .font1{
          font-weight: bold;
          font-size: large;
        }

        #t,#b{
          border-collapse: collapse;
          margin: 30px auto;
          width: 600px;
        }
        #t thead{
          border: 3px solid gold;
          color: white;
          background-color: blue;
        }
        #t tbody{
          color: #1414bf;
          background-color: white;
        }
</style>

js part

<script src="../lib/jquery-3.3.1.js"></script>
  <script>
    //Initialize button function initButton(){
      $("input[name=j1]").off();
      $("input[name=x1]").off();
      //Add quantity button $("input[name=j1]").on("click", function (){
             var num = parseInt($(this).prev().val());
        if (num > 1){
          $(this).prev().prev().attr("disabled",false);
        }
        if (num > 9){
          $(this).attr("disabled","disabled");
          return;
        }
             num++;
             if (num > 1){
               $(this).prev().prev().attr("disabled",false);
             }
             if (num > 9){
               $(this).attr("disabled","disabled");
             }
             $(this).prev().val(num);
        $("#Total").text(cal());
        $("#TotalNum").text(calNum());
           }
      )
      //Decrease quantity button$($("input[name=x1]")).click(function (){
        var num = parseInt($(this).next().val());
        if (num-1 < 10){
          $("#add1").prop("disabled",false);
        }
        num--;
        if (num < 10){
          $(this).next().next().prop("disabled",false);
        }
        if (num == 1){
          $(this).prop("disabled","disabled");
        }
        $(this).next().val(num);
        $("#Total").text(cal());
        $("#TotalNum").text(calNum());
      });
    }
// Initialize deletion function initdelete(){
      $(".delete").on("click",function (){
        $(this).parent().parent().remove();
        $("#Total").text(cal());
        $("#TotalNum").text(calNum());
      });
    }
//Select all or unselect all function$("thead input[type=checkbox]").on("click",function (){
     $("tbody input[type=checkbox]").each(function (index,element){
       $(this).prop("checked",$("thead input[type=checkbox]").prop("checked"));
       $("#Total").text(cal());
       $("#TotalNum").text(calNum());
     });
   })

    // Initialize each checkbox function initCheckBox(){
      $("tbody input[type=checkbox]").off();
      $("tbody input[type=checkbox]").on("change",function (){
        $("#Total").text(cal());
        $("#TotalNum").text(calNum());
      });
    }
    //Calculate the total price function cal(){
      var price = null;
      $("tbody input[type=checkbox]:checked").each(function (){
        var priceByOne = parseFloat($(this).parent().next().next().text());
        var num = parseFloat($(this).parent().next().next().next().find("input[name='num']").val());
        var totalMoneyByone = priceByOne * num;
        price+= totalMoneyByone;
      });
      return price;
    }
    //Calculate the total number function calNum(){
      var totalNum = null;
      $("tbody input[type=checkbox]:checked").each(function (){
        var num = parseInt($(this).parent().next().next().next().find("input[name='num']").val());
        totalNum+=num;
      });
      return totalNum;
    }


    //Settlement$("#pay1").on("click",function (){

      alert("Total consumption: "+cal());
      $("thead input[type=checkbox]:checked").prop("checked",false);
      $("tbody input[type=checkbox]:checked").parent().parent().remove();


    });

    //Add$("#add1").on("click",function (){
      var name = $("#name").val();
      var price = $("#price").val();
      var priceZ = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/
      if ((name == "" || price == "") || (!priceZ.test(price)) ){
        alert("Input error!");
      }else {
        var GameArr = [];
        var flag = false;
        var repeat = null;
        //Get the name array $("tbody").each(function (){
            var finds = $(this).find(".goodsName");
            for (let i = 0; i < finds.length; i++) {
              GameArr.push(finds.eq(i).text());
          }
        });
        for (let i = 0; i < GameArr.length; i++) {
          if (name == GameArr[i]){
            repeat = i;
            flag = true;
            break;
          }}
        //If there is a same name, change the quantity and price if (flag == true){
          var totalNum = parseInt($("tbody:eq(" + repeat + ")").find("input[name='num']").val())+1;
          if (totalNum > 9){
            $(this).attr("disabled","disabled");
          }
          $("tbody:eq(" + repeat + ")").find("input[name='num']").val(totalNum);
          $("tbody:eq(" + repeat + ")").find(".goodsPrice").text(price);
          //Otherwise concatenate the tables}else {
        var goods = "<tr>"+
             "<td><input type='checkbox' style='cursor: pointer'></td>"+
             "<td class='goodsName'>"+name+"</td>"+
             "<td class='goodsPrice'>"+price+"</td>"+
             "<td>"+
             "<input type='button' value='-' name='x1' style='cursor: pointer'>&nbsp;"+
             "<input type='text' value='1' name='num'>&nbsp;"+
             "<input type='button' value='+' name='j1' style='cursor: pointer'>"
             +"</td>"+
             '<td><a href="" class=" rel="external nofollow" delete" style="color:red">Delete</a></td>' +
             "</tr>"
        $("tbody").append(goods);
        //After adding each time, bind the event initButton();
        initdelete();
        initCheckBox();
      }}
    });
</script>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Detailed explanation of the working principle and solution of Js modularization
  • What are the core modules of node.js
  • Usage of Node.js http module
  • Detailed explanation of the difference between exports and module.exports in nodejs
  • Detailed explanation of the difference between Module.exports and exports in Sea.js
  • The difference between module.exports and exports in node.js
  • Detailed introduction to the difference between exports and module.exports in nodejs
  • Specific usage of require.js for advanced JavaScript modularization
  • Detailed explanation of the official tutorial of RequireJs
  • Usage and difference of Js module packaging exports require import

<<:  Centos7.3 How to install and deploy Nginx and configure https

>>:  How to automatically number the results of MYSQL query data

Recommend

Implementation of postcss-pxtorem mobile adaptation

Execute the command to install the plugin postcss...

MySQL derived table (Derived Table) simple usage example analysis

This article uses an example to describe the simp...

Analysis and description of network configuration files under Ubuntu system

I encountered a strange network problem today. I ...

Example of exporting and importing Docker containers

Table of contents Exporting Docker containers Imp...

How to implement h5 input box prompt + normal text box prompt

XML/HTML CodeCopy content to clipboard < input...

HTML tutorial, HTML default style

html , address , blockquote , body , dd , div , d...

JavaScript object-oriented class inheritance case explanation

1. Object-oriented class inheritance In the above...

How to set the width and height of html table cells

When making web pages, you often encounter the pr...

An article to help you understand jQuery animation

Table of contents 1. Control the display and hidi...

Description of the execution mechanisms of static pages and dynamic pages

1. A static page means that there are only HTML ta...

MySQL chooses the appropriate data type for id

Table of contents Summary of Distributed ID Solut...

Docker exposes port 2375, causing server attacks and solutions

I believe that students who have learned about th...

Detailed explanation of how to select all child elements using CSS

How to recursively select all child elements usin...

Solution to the error problem of Vscode remotely connecting to Ubuntu

1. Background of the incident: Because of work ne...