Shopping Cart Front-End development (jquery and BOOTSTRAP3) _javascript tips

Source: Internet
Author: User

As a software engineer who does not work in a software company, it is not only to write back code (Php/java/sql ...), but also to take into account the work of the front-end Engineers (HTML/JAVASCRIPT/CSS ...). Here's how to share the front-end development of a shopping cart that is used in a real-world work project.

What is shared here is simply the operation of the shopping cart (the increase in the number of products, the deletion of items in the shopping cart), and the assumption that there are several products already in the shopping cart. Less gossip, first on the two effect picture.

The HTML code is as follows: JQuery1.11 and BOOTSTRAP3 are used here.

<! DOCTYPE html>  

The HTML code is divided into two major chunks, the table section is used to display the product details in the cart, and a div is used to display the summary information later. Here's a technique that needs to be specifically described:

1. Specify some false class names (style names that do not exist in the style sheet) for the element to facilitate the use of the jquery filter to find specific elements. Like the style in the above code check-all/check-one/cart/subtotal

JavaScript code needs to implement the following features:

1. All Product selection function

2. Calculate product subtotal (i.e. product unit price * Purchase quantity)

3. The user selects a product model in the shopping cart and needs to recalculate the summary information below the page, including the selected product model type, product quantity subtotal and amount subtotal

4. When a user deletes a product model from a shopping cart or modifies the purchase quantity, the summary information below the page needs to be recalculated.

Here are the above features one by one instructions:

1. All Product selection function

$ (carttable). Find (": CheckBox"). Click (function () {
  //Select All box (
  $ (this). Hasclass ("Check-all")) {
   var Checked = $ (this). Prop ("checked");
   $ (carttable). Find (". Check-one"). Prop ("checked", checked);

  If you manually select all of the check boxes one by one, you need to automatically check "Select All" or cancel the
  var items = Carttable.find ("tr:gt (0)");
  $ (carttable). Find (". Check-all"). Prop ("Checked", Items.Find (": checkbox:checked"). Length = = items.length);

  Gettotal ();
 });

Bind an event to each of the same selection boxes in the shopping cart table. In this event, you need to determine whether the user clicks on the "Select All" selection box, or each product's own selection box, then once again used the above mentioned false style. What needs to be specifically described here is that jquery reads the attributes of an element usually using the attr () method, but for a checkbox, using attr () does not correctly read to its Checked property value. The correct usage is to read using the prop () method.

If the user clicks "Select All", then all the selection boxes should be selected, which is easy to take into account. But one of the details that needs to be noticed is that when the user manually selects all the products one at a time, the program should also set the Select All box to the selected state, or in all the selected state, the user manually canceled a product selected state, then the program should be the "Select All" box is not selected.

The last line of code is to recalculate the summary information for the cart after the user has chosen to do so.

2. Product Subtotal Function code:

 
  * * Calculate the amount of each product line in the shopping cart subtotal
  * *
  parameters row in cart TABLE element TR
  * *
 /function getsubtotal (row) {
 var price = Parsefloat ($ (row). Find ("Span:first"). Text ()); Get unit value
  var qty = parseint ($ (row). Find (": Text"). Val ());//Get quantity
  var result = Price * QTY;//Subtotal
  $ (row). Find (". Subtotal"). Text (result.tofixed (2)); Writes a subtotal of the calculated amount to the Subtotal field
 };

This function needs to pass in a parameter, the TR element used to display the contents of the shopping cart.
In the table showing the contents of the shopping cart, each product unit price is wrapped with a span element, and is the first SPAN element in the line, using the jquery filter $ (row). Find ("Span:first") can be located to the product unit price, using its text function to read content and uses parsefloat to convert the read string to a floating-point number.
Purchase quantity, because the user may change, so use input to show. Colleagues, use a filter like this to navigate to the number
$ (row). Find (": Text")

and use parseint to convert it to an integer. After you have calculated a subtotal for a single product amount, you need to write it to the Subtotal field and use the Tofixed method to format the number with a two-bit decimal style.

3. Total Shopping Cart Amount

 * *
  Calculate the cumulative amount of the product in the cart
  *
  * *
 /function Gettotal () {
 var qtytotal = 0;
  var itemCount = 0;
  var pricetotal = 0;
  $ (carttable). Find ("tr:gt (0)"). each (function () {
  if (.) ($ (this). Find (": CheckBox"). Prop ("checked") = = True) {//If selected
    itemcount++//Cumulative product variety number
    Qtytotal + = parseint ($ (this). Find (": Text"). Val ());//cumulative number of products purchased
    Pricetotal = Parsefloat ($ (this). Find (". Subtotal"). text ()); Cumulative product Amount
   }
  });    $ ("#itemCount"). Text (itemCount);
  $ ("#qtyCount"). Text (qtytotal);
 $ ("#priceTotal"). Text (pricetotal.tofixed (2));
 

When calculating cart summary information, you should iterate through all the rows in the shopping cart, and add up the subtotals and the number of each line separately. Here's a trick to get all the rows in the Cart table $ (carttable). Find ("tr:gt (0)")

The TR:GT (0) used here is to represent all the TR elements in the selection table and the index is greater than 0 (that is, to remove the first TR element). When we look back at the HTML code, it's easy to see that the first TR element is a table header and does not contain any business data, so you should drop this TR element when traversing.

4. Recalculate product Subtotal and summary information when a user deletes a product or modifies a purchase quantity

Provide click events for number-adjusted +-numbers, and recalculate subtotal/* For each line of the cart, bind the event, and the input box in each row binds the keyboard event * performs different actions according to the element that triggers the event * Increase quantity * Reduce quantity * Delete product * 
 */$ (carttable). Find ("tr:gt (0)"). each (function () {var input = $ (this). Find (": Text");
 Adds an event for the quantity input box, calculates a subtotal, and updates total $ (input). KeyUp (function () {var val = parseint ($ (this). Val ()); if (isNaN (val) | | (Val < 1))
  {$ (this). Val ("1");} Getsubtotal ($ (this). Parent (). parent ());
 TR element Gettotal ();

 });
 Adjust the button for the quantity, delete the Add click event, calculate the subtotal for the amount, and update the total $ (this). Click (function () {var val = parseint ($ (input). val ()); if (isNaN (val) | | (Val < 1))

 {val = 1;}
   if ($ (window.event.srcElement). Hasclass ("minus")) {if (Val > 1) val--;
   Input.val (Val);
  Getsubtotal (this);
  else if ($ (window.event.srcElement). Hasclass ("plus")) {if (Val < 9999) val++;
 Input.val (Val);
  Getsubtotal (this); else if ($ (window.event.srcElement). Hasclass ("delete") {if confirm ("OK) to remove this product from the shopping cart?"
 ")) {$ (this). Remove ();
 } gettotal ();

 });

I'm not here one by one. For the add, reduce, and delete buttons to bind to events, the Click event is uniformly bound on the TR line, and then the element that triggers the Click event is judged and then the action is determined.

When you click the "+" or "-" button, the program adds one or more numbers and recalculates the product subtotal and summary information.

The keyboard event is also bound for the quantity input box, and every time the keyboard is pressed in the input box, the event is triggered to recalculate the product subtotal and summary information.

At this point, the shopping cart front-end development, is the end.

Small partners can use the following links to obtain source code: Https://github.com/chris-mao/ShoppingCart.git

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.