Home Web Front-end JS Tutorial How to implement floating shopping cart with js cookies_javascript skills

How to implement floating shopping cart with js cookies_javascript skills

May 16, 2016 pm 03:57 PM
cookies js shopping cart

The example in this article describes how to implement a floating shopping cart using js cookies. Share it with everyone for your reference. The specific analysis is as follows:

Create a “no-refresh shopping cart” that combines “floating” and “DataList” on the “product list display page”. You only need to calculate the total price without going to a separate page for settlement. I found some information and modified it, and the examples are as follows:

gwc.js file is as follows:

// JavaScript Document
//计算单个小计
 function EveryCount()
 {
  var index=window.event.srcElement.parentElement.parentElement.rowIndex;
  var a=document.getElementById("test").rows(index).cells(1).innerText;
  var b=document.getElementById("Num"+index).value;
  var c=parseFloat(a)*parseFloat(b);
  document.getElementById("test").rows(index).cells(3).innerText=c;
  TotalCount();
  updateOrderCookie();//修改cookies中保存的数量
 }
//计算总计
function TotalCount()
{
  var rowscount=document.getElementById("test").rows.length;
  var sum=0;
  for(var i=1;i<=(parseInt(rowscount)-1);i++)
  {
    var littecount=document.getElementById("test").rows(i).cells(3).innerText;
    sum=parseFloat(sum)+parseFloat(littecount);
  }
  document.getElementById("total").innerText=sum;
}
//<--Start--将订单数据写入div
function WriteOrderInDiv()
{
 var gwc="<table id='test' style='border:0px;' ><tr><td width='40%'>商品名称</td><td>单价(¥)</td><td>数量</td><td>小计</td></tr>";
 var OrderString=unescape(ReadOrderForm('24_OrderForm'));//获取cookies中的购物车信息
 //document.write(OrderString);
 var strs= new Array(); //定义一个数组,用于存储购物车里的每一条信息
 var OneOrder="";
 //strs=OrderString.split("%7C");//用|分割出购物车中的每个产品
 strs=OrderString.split("|");//用|分割出购物车中的每个产品
 for (i=1;i<strs.length ;i++ )  
 {
 gwc+="<tr>";
 //OneOrder=strs[i].split("%26");
 OneOrder=strs[i].split("&");
 for (a=1;a<OneOrder.length ;a++ )  
 {
  if(a!=3)
  {
  gwc+="<td>";
  gwc+=OneOrder[a];
  gwc+="</td>";
  }
  else
  {
  gwc+="<td id='dd'>";
  gwc+="<input title='填写想购买的数量,请使用合法数字字符' style='width:10px;' id='Num"+i+"' type='text' onkeyup='EveryCount();'value='"+OneOrder[a]+"'>";
  gwc+="</td>";
  }
  //document.getElementById("gwc").innerHTML+=OneOrder[a]+"<br/>";//每个产品的每个属性分割后字符输出
 }
 gwc+="<td>";
  gwc+=OneOrder[2]*OneOrder[3];
  gwc+="</td>";
  gwc+="</tr>";
    //document.getElementById("gwc").innerHTML+=strs[i]+"<br/>";  //每个产品分割后的字符输出
  }
 gwc+="</table>";
 document.getElementById("Cart").innerHTML=gwc;
 TotalCount();
}
//<--End--将订单数据写入div
//--Start--展开/收缩购物车
function show(id)
{
if (document.getElementById(id).style.display=="") 
{
document.getElementById(id).style.display='none';
}
else{document.getElementById(id).style.display='';
}
}
//<--End--展开/收缩购物车
//<--Start--从cookie中读出订单数据的函数
function ReadOrderForm(name)
{
  var cookieString=document.cookie;
  if (cookieString=="")
  {
    return false;
  }
  else
  {
    var firstChar,lastChar;
    firstChar=cookieString.indexOf(name);
    if(firstChar!=-1)
    {
      firstChar+=name.length+1;
      lastChar = cookieString.indexOf(';', firstChar);
      if(lastChar == -1) lastChar=cookieString.length;
      return cookieString.substring(firstChar,lastChar);
    }
    else
    {
      return false;
    }
  }  
}
//-->End
//<--Start--添加商品至购物车的函数,参数(商品编号,商品名称,商品数量,商品单价)
function SetOrderForm(item_no,item_name,item_amount,item_price)
{
  var cookieString=document.cookie;
  if (cookieString.length>=4000)
  {
    alert("您的订单已满\n请结束此次订单操作后添加新订单!");
  }
  else if(item_amount<1||item_amount.indexOf('.')!=-1)
  {
    alert("数量输入错误!");
  }
  else
  {
    var mer_list=ReadOrderForm('24_OrderForm');
    var Then = new Date();
    Then.setTime(Then.getTime()+30*60*1000);
    var item_detail="|"+item_no+"&"+item_name+"&"+item_price+"&"+item_amount;
    if(mer_list==false)
    {
      document.cookie="24_OrderForm="+escape(item_detail)+";expires=" + Then.toGMTString();
      alert("“"+item_name+"”
"+"已经加入您的订单!");
    }
    else
    {
      if (mer_list.indexOf(escape(item_no))!=-1)
      {
        alert('此商品您已添加
请进入订单修改数量!')
      }
      else
      {
        document.cookie="24_OrderForm="+mer_list+escape(item_detail)+";expires=" + Then.toGMTString();
        alert("“"+item_name+"”
"+"已经加入您的订单!");
      }
    }
  }
}
//-->End
//<--Start--修改数量后,更新cookie的函数
function updateOrderCookie()
{
 var rowscount=document.getElementById("test").rows.length;
  var item_detail="";
  for(var i=1;i<=(parseInt(rowscount)-1);i++)
  {
    item_detail+="|"+document.getElementById("test").rows(i).cells(0).innerText+"&"+document.getElementById("test").rows(i).cells(0).innerText+"&"+document.getElementById("test").rows(i).cells(1).innerText+"&"+document.getElementById("Num"+i).value;
   // document.write(document.getElementById("test").rows(i).cells(1).innerText);
  }
 var Then = new Date();
 Then.setTime(Then.getTime()+30*60*1000);
 document.cookie="24_OrderForm="+escape(item_detail)+";expires=" + Then.toGMTString();
}
//<--End--订单更新
//<--清空购物车
function clearOrder() 
{
var Then = new Date();
document.cookie="24_OrderForm='';expires=" + Then.toGMTString();
}
//<--End

Copy after login

gwc.html file is as follows:

<script src="js/gwc.js" type="text/javascript"></script>
<div width="300px">
 <div id="Cart" style="line-height: 24px; font-size: 12px; background-color: #f0f0f0;
 border-top: 1px #ffffff solid;display:none; ">
 </div>
 <div id="Info">
      总计:<strong><span id="total" style="color: #FF0000; font-size: 36px">0</span></strong>元
  <input type="button" value="清空" onclick="clearOrder();WriteOrderInDiv();" />
  <input type="button" value="展开/收缩" onclick="show('Cart')" />
 </div>
 <input type="button" value="加入商品1" onclick="SetOrderForm('NO1','商品1','1','3.5');WriteOrderInDiv();" />
 <input type="button" value="加入商品2" onclick="SetOrderForm('NO2','商品2','1','5.5');WriteOrderInDiv();" />
 <input type="button" value="加入商品3" onclick="SetOrderForm('NO3','商品3','1','10.5');WriteOrderInDiv();" />
 </div>
  <script>
  window.WriteOrderInDiv();
  </script>

Copy after login

The function of the above js is to obtain and output the order information after the page is opened.

The example is written in HTML. In the DataList, you only need to bind the parameters in onclick="SetOrderForm('NO3','Product 3','1','10.5'); of the add product button , just set the outer div to float on the right side of the browser

.

I hope this article will be helpful to everyone’s JavaScript programming design.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to implement a simple shopping cart function in Java? How to implement a simple shopping cart function in Java? Nov 02, 2023 am 11:56 AM

How to implement a simple shopping cart function in Java? The shopping cart is an important feature of an online store, which allows users to add items they want to purchase to the shopping cart and manage the items. In Java, we can implement a simple shopping cart function by using object-oriented approach. First, we need to define a product category. This class contains attributes such as product name, price, and quantity, as well as corresponding Getter and Setter methods. For example: publicclassProduct

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

Practical tutorial: Detailed explanation of shopping cart function with PHP and MySQL Practical tutorial: Detailed explanation of shopping cart function with PHP and MySQL Mar 15, 2024 pm 12:27 PM

Practical tutorial: Detailed explanation of the shopping cart function with PHP and MySQL. The shopping cart function is one of the common functions in website development. Through the shopping cart, users can easily add the goods they want to buy to the shopping cart, and then proceed with settlement and payment. In this article, we will detail how to implement a simple shopping cart function using PHP and MySQL and provide specific code examples. To create a database and data table, you first need to create a data table in the MySQL database to store product information. The following is a simple data table

See all articles