Native js implements shopping cart logic and functions

Native js implements shopping cart logic and functions

This article example shares the specific code of js to implement the shopping cart logic and functions for your reference. The specific content is as follows

1. Try to use a table layout for the main content of the shopping cart

2. Determine whether the user is logged in

The code is as follows, which can be modified according to the layout of your own header

// Determine whether the user is logged in var username = getCookie("username");
//If the login is successful, execute this code if(username){
    var vip = $(`<a href='javascript:;'>Welcome <b>${username}</b> to Tmall Supermarket</a>`)
    var loginout = $(`<a href='javascript:;' class="loginout">Logout</a>`)
    $(".hLeft").empty()
    $(".hLeft").append(vip)
    $(".hLeft").append(loginout)
    $(".hLeft>a").css({
        "color":"#666",
        "lineHeight":"32px",
        "marginLeft":"10px"
    })
    $(".hLeft>a>b").css({
        "color":"red",
        "fontWeight":"800",
    })
    $(".loginout").click(function(){
        removeCookie("username")
        $(".hLeft").empty()
        $(".hLeft").html(` <a href="home.html" >Tmall Home Page</a>
        <a href="javascript:;" >Meow, welcome to Tmall</a>
        <a href="login.html" >Please log in</a>
        <a href="register-test.html" >Free registration</a>`)
    })
}else{
    alert("Please log in first");
    location.assign("./login.html");
}

3. Determine whether there is data transmitted from the details page

Here my data is saved in local storage. You can get the data according to your storage location. The code is as follows:

// Receive data from the details page // First determine whether there is a product in the local storage var data = localStorage.getItem("cart");
if(!data){
    $(".page-con").empty();
    var str = "";
    str +=`<h2>The shopping cart is empty! ! ! </h2>
    <p>Please quickly move to the list page and select the product to <p><a href="./list.html" >enter the list page</a>
    `
    $(".page-con").html(str);
    $(".page-con").css({width:"900px",margin:"40px auto 0"});
    $(".page-con h2").css({fontSize:"50px",color:"blue",lineHeight:"80px"})
    $(".page-con p").css({fontSize:"20px",lineHeight:"26px"});
    $(".page-con a").css({width:"100px",height:"40px",background:"skyblue",marginTop:"20px",display:"block"})
}else{
    // Then determine whether the current user's shopping cart is data // Convert the data into an array type data = JSON.parse(data);
    // Check if the data exists for(var j=0;j<data.length;j++){}
    var res = data.some(v=>{
        return v.username == username;
    })
    if(!res){
        $(".page-con").empty();
        var str = "";
        str +=`<h2>The shopping cart is empty! ! ! </h2>
        <p>Please quickly move to the list page and select the product to <p><a href="./list.html" >enter the list page</a>
        `
        $(".page-con").html(str);
        $(".page-con").css({width:"900px",margin:"40px auto 0"});
        $(".page-con h2").css({fontSize:"50px",color:"blue",lineHeight:"80px"})
        $(".page-con p").css({fontSize:"20px",lineHeight:"26px"});
        $(".page-con a").css({width:"100px",height:"40px",background:"skyblue",marginTop:"20px",display:"block"})
    }else{
        // There is data and it has its own data // Find out your own data first var arr = data.filter(v=>v.username == username);
        // Traverse the acquired data // There is no desired product data in the array, so you need to get it from the database and search for data in the database by id var ids = arr.map(v=>v.goodsid);
        
        ids = ids.join(",")

4. When querying the data sent from the detail page, we can use the ID sent to find the data we want in the database

Send ajax to the database to find product information

$.ajax({
            url:"./server/cart.php",
            dataType:"json",
            data:{ids:ids},
            type:"get",
            success:res=>{
                var str = '';
                for(var i=0;i<res.length;i++){
                    // According to each item in res[i], find the number of number from arrvar number = arr.find(v=>v.goodsid==res[i].id).number;
                    
                    str +=`
                        <div class="pageMtop">
                            <input type="checkbox" name="onetop"><i></i><span>Store: ${res[i].name}</span><em></em>
                        </div>
                        <div class="pageMcontent">
                            <h3><img src="images/cat10.png">8.6 0 o'clock, every 300 minus 30</h3>
                            <ul>
                                <li>
                                    <input type="checkbox" name="one">
                                </li>
                                <li>
                                    <a href="#" >
                                        <img src="${res[i].imgpath}">
                                    </a>
                                </li>
                                <li>
                                    <p>
                                        <a href="#" >${res[i].introduce}</a>
                                    </p>
                                    <img src="images/cat03.png" alt="">
                                    <a href="javascript:;" ><img src="images/cat04.png" alt=""></a>
                                </li>
                                <li>
                                    <p>Size: M</p>
                                    <p>Main colors: 6685 white + 6691 haze blue (M size pre-sale will be issued on August 8th</p>
                                    <a href="#" >Edit</a>
                                </li>
                                <li>
                                    <span>${res[i].price}</span>
                                </li>
                                <li class="data-name" data-id = "${res[i].id}">
                                <input type="button" class="reduce" value="-">
                                <input class="numberone" type="number" name="number" data-stock="${res[i].stock}" value="${number}">
                                <input type="button" class="add" value="+">
                                </li>
                                <li class="subtotal">
                                    ${res[i].price*number}
                                </li>
                                <li>
                                    <p>Move into folder</p>
                                    <p class="btn">Delete</p>
                                    <p>Baby</p>
                                </li>
                            </ul>
                        </div>
                    `
                }
                $(".page-middle").html(str)
                 //Add the select all function here // If you write it here, the code will be too deeply nested - write the function outside and then call the function here //Call the select all function selectAll()
                //Call the single selection function selectone()
                // Calculate the total price and total quantity priceAndNumberAll()
                // Add and subtract quantities addAndReduce()
                // Click the delete key removebtn()
            }
        })
    }

Here we need to dynamically load the layout and content rendering of the product column, and then add it to the big box where the main content is placed.

5. Implement the functions of the shopping cart page

Because there are many functional codes, putting them all in ajax will be redundant. We encapsulate each function into a function and call it directly in the callback function after ajax is completed.

6. Select All Function

The code is as follows:

//Select all function function selectAll(){
    // Bind events to both top and bottom selections $("[name='topAll']")[0].onclick = $("[name='footAll']")[0].onclick = function(){
        // Set the state of the single selection $("[name='one']").prop("checked",$(this).prop("checked"))
        $("[name='onetop']").prop("checked",$(this).prop("checked"))
        // Add all selections to both checkboxes $("[name='topAll']").prop("checked",$(this).prop("checked"))
        $("[name='footAll']").prop("checked",$(this).prop("checked"))
        priceAndNumberAll()
    }
}

7. Single-select function

The code is as follows:

// Single-select function function selectone(){
    $("[name='one']").click(function(){
        // Check if all are checked //$("[name='one']") is a pseudo-array, you cannot call array methods to convert it into an array first $("[name='onetop']").prop("checked",$(this).prop("checked"))
        var arr = Array.prototype.slice.call($("[name='one']"))
        // Call the every method and return false if one is not selected
        var res = arr.every(v=>$(v).prop("checked"));
        if(res){
            $("[name='topAll']").prop("checked","checked");
            $("[name='onetop']").prop("checked","checked");
            $("[name='footAll']").prop("checked","checked");
        }else{
            $("[name='topAll']").prop("checked",false);
            $("[name='footAll']").prop("checked",false)
        }
        priceAndNumberAll()
    })
}

8. Calculate the total quantity and total price

The code is as follows:

// Calculate the total price and total quantity function priceAndNumberAll(){
    // Calculate based on the selected box // Select the selected number
    var allNumInput = $("[name='one']:checked").parent().siblings(".data-name").find("[name='number']")
    var allNum = 0;
    allNumInput.each(function(k,v){
        allNum += v.value-0;
    })
    $(".allnumber").text(allNum);
    var allPriceEle = $("[name=one]:checked").parent().siblings(".subtotal")
    var allPrice = 0;
    allPriceEle.each(function(k,v){
        allPrice += allPriceEle.text()-0;
    })
    $(".allprice").text(allPrice);
}

9. Click the plus and minus buttons to add and subtract quantities and amounts.

The code is as follows:

// Click on addition and subtraction to add or subtract quantities function addAndReduce(){
    // Click the add button $(".add").click(function(){
        // First get the value in the input box var num = $(this).prev().val()-0;
        // Every time you click, the value in the input is ++
        num++
        // Data cannot be added wirelessly. If it reaches the maximum value, it will not be added if (num>=$(this).prev().attr("data-stock")-0) {
            num=$(this).prev().attr("data-stock")-0
            $(this).prop("disabled",true);
            $(this).addClass("bgadd");
            $(this).prev().prev().prop("disabled",false);
        }else{
            $(this).prop("disabled",false);
            $(this).prev().prev().removeClass("bgreduce");
        }
        $(this).prev().val(num)
        // Calculate the price in the subtotal // Find the label and value for the unit price var price = $(this).parent().prev().find("span").text()-0;
        // Recalculate subtotal var subtotal = price*num;
        // After calculating the subtotal, put it in the storage td $(this).parent().next().text(subtotal);
        // Reset local storage // Get local storage data var data = localStorage.getItem("cart");
        // Convert to array data = JSON.parse(data);
        // Traverse the array to find the data that meets the conditions in the array var obj = data.find(v=>v.username==username && v.goodsid==$(this).parent().attr("data-id"));
        obj.number = num;
        localStorage.setItem("cart",JSON.stringify(data))
        priceAndNumberAll()
    })
    $(".reduce").click(function(){
        // First get the value in the input box var num = $(this).next().val()-0;
        // Every time you click, the value in the input is ++
        num --
        // Data cannot be added wirelessly. If it reaches the maximum value, it will not be added if (num < 1) {
            num=1;
            $(this).prop("disabled",true);
            $(this).addClass("bgreduce");
            $(this).next().next().prop("disabled",false)
        }else{
            $(this).prop("disabled",false);
            $(this).next().next().removeClass("bgadd");
        }
        $(this).next().val(num)
        
        var price = $(this).parent().prev().find("span").text()-0;
        // Recalculate subtotal var subtotal = price*num;
        // After calculating the subtotal, put it in the storage td $(this).parent().next().text(subtotal);
        // Store the data back to local storage var data = localStorage.getItem("cart");
        data = JSON.parse(data);
        // Find the data that meets the requirements var obj = data.find(v=>{
            return v.username==username&&v.goodsid==$(this).parent().attr("data-id");
        })
        obj.number = num;
        localStorage.setItem("cart",JSON.stringify(data));
        priceAndNumberAll()
    })
}

10. Click the delete button function

The code is as follows:

//Click to delete function function removebtn(){
    // Click event $(".btn").click(function(){
        // Prompt whether to delete if(!confirm("Are you sure you want to delete")){
            return false;
        }
        // Delete the locally stored data var data = localStorage.getItem("cart");
        data = JSON.parse(data);
        var index = data.findIndex(function(v){
            v.username==username&&v.goodsid==$(this).parent().siblings(".data-name").attr("data-id")
        });
        data.splice(index,1);
        localStorage.setItem("cart",JSON.stringify(data))
        var tr = $(this).parent().parent();
        tr.remove()
        if(!data.filter(v=>v.username==username).length){
            // If there is no data, the table will not be displayed $(".page-middle").empty();
            // Let the page display custom content var str = "";
            str += `<h2>The shopping cart is empty! ! ! </h2>
        <p>Please quickly move to the list page and select the product to <p><a href="./list.html" >enter the list page</a>
        `
        $(".page-middle").html(str);
        $(".page-middle").css({width:"1200px",margin:"40px auto 0"});
        $(".page-middle h2").css({fontSize:"50px",lineHeight:"80px",color:"blue"})
        }

    })
}

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:
  • Vuejs teaches you step by step to write a complete shopping cart example code
  • js shopping cart implementation ideas and code (personally feel good)
  • Writing a simple shopping cart function in JavaScript
  • Javascript detailed code to implement shopping cart function
  • js implements a simple shopping cart with pictures and codes
  • Jsp+Servlet to realize shopping cart function
  • Javascript manipulates Cookies to implement shopping cart program
  • Simple front-end js+ajax shopping cart framework (beginner's guide)
  • Native js simulation Taobao shopping cart project practice
  • js to achieve shopping cart addition and subtraction effects

<<:  How to build a tomcat image based on Dockerfile

>>:  Let's talk about parameters in MySQL

Recommend

Three.js sample code for implementing dewdrop animation effect

Preface Hello everyone, this is the CSS wizard - ...

How to use geoip to restrict regions in nginx

This blog is a work note environment: nginx versi...

Example of how to quickly build a LEMP environment with Docker

LEMP (Linux + Nginx + MySQL + PHP) is basically a...

How to use Dockerfile to create a mirror of the Java runtime environment

The current environment is: Centos 7.5 docker-ce ...

An article teaches you JS function inheritance

Table of contents 1. Introduction: 2. Prototype c...

Four ways to compare JavaScript objects

Table of contents Preface Reference Comparison Ma...

Detailed explanation of Vue's keyboard events

Table of contents Common key aliases Key without ...

Win10 + Ubuntu 16.04 dual system perfect installation tutorial [detailed]

Be sure to remember to back up your data, it is p...

Docker packages the local image and restores it to other machines

1. Use docker images to view all the image files ...

HTML meta viewport attribute detailed description

What is a Viewport Mobile browsers place web pages...

Using JS to determine the existence of elements in an array in ten minutes

Preface In front-end development, you often need ...

Detailed explanation of several storage methods of docker containers

Table of contents Written in front Several storag...

Win32 MySQL 5.7.27 installation and configuration method graphic tutorial

The installation tutorial of MySQL 5.7.27 is reco...

Nginx access log and error log parameter description

illustrate: There are two main types of nginx log...