Shopping Cart front-end development

Source: Internet
Author: User

As a software engineer who does not work in a software company, he will not only write background code (Php/java/sql ...), but also work with front-end engineers (Html/javascript/css ...). Here's how to share a front-end development of a shopping cart used in a real work project.

The only things that are shared here are the operations for the shopping cart (the increase in the number of products is reduced and the items in the shopping cart are deleted), assuming that there are several products in the cart. Gossip less say, first two Zhang.




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

<! DOCTYPE html>
The HTML code is divided into two main chunks, the table section is used to display the product details in the cart, followed by a DIV used to display the summary information. Here's a tip that needs to be specifically explained:

1. Specify some false class names for the elements (style names that do not exist in the stylesheet), which makes it easy to use jquery's filters to find specific elements. As in the code above, the style check-all/check-one/cart/subtotal


The JavaScript code needs to implement several features:

1. Full Product selection function

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

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

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


The following features are described above one by one:

1. Full Product selection function

$ (carttable). Find (": CheckBox"). Click (function () {        //Select All box ().        hasclass ("Check-all") {            var Checked = $ (this). Prop ("checked");            $ (carttable). Find (". Check-one"). Prop ("checked", checked);        }        If you select all the checkboxes manually by one point, you need to automatically tick "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 ();    });
For each of the boxes in the shopping cart table, bind the order-click event. In this event, you need to determine whether the user clicked the "Select All" box, or each product's own selection box, then here again to use the above mentioned false style. It is particularly important to note that jquery reads the attributes of an element typically 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 selection boxes should be selected, which is easy to consider. However, there is a detail to note, that is, when the user manually one of the products selected, the program should be the "Select All" box is also selected, or in all selected state, the user manually canceled a product selected, then the program should also set the "Select All" box is unchecked.

The last line of code is to recalculate the summary information for the shopping cart after the user has finished selecting it.

2. Product Subtotal Function code:

         /* * Calculate the amount of each product line in the cart subtotal     *     * parameter row in cart TABLE element TR     * *    /function getsubtotal (row) {var price = parsefloat (Row). Find ("Span:first"). Text ()); Gets the unit price        var qty = parseint ($ (row). Find (": Text"). Val ());//Gets the quantity        var result = prices * QTY;//Calculates the amount in subtotal        $ (row). Find (". Subtotal"). Text (result.tofixed (2)); Writes the calculated amount subtotal to the Subtotal field    };

This function needs to pass in a parameter, which is 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 row, using the jquery filter
$ (row). Find ("Span:first")
That is, you can locate the product unit price, use its text function to read the content, and use parsefloat to convert the read string to a floating-point number.

Purchase quantity, because the user may change, so use input to show. Colleague, use the filter below to locate the quantity

$ (row). Find (": Text")

and use parseint to convert it to an integer. Once the individual product amount subtotal is calculated, it needs to be written to the Subtotal field, using 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 (": CheckBox"). Prop ("checked") = = True) {//If selected                itemcount++;//Cumulative product Variety Quantity                Qtytotal + = parseint ($ (this). Find (": Text"). Val ());//Cumulative product Purchase Quantity                Pricetotal + = Parsefloat ($ (this). Find (". Subtotal"). text ()); Cumulative product Amount            }        });       
        $ ("#itemCount"). Text (itemCount);        $ ("#qtyCount"). Text (qtytotal); $ ("#priceTotal"). Text (pricetotal.tofixed (2));    };

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

The TR:GT (0) used here represents the selection of all the TR elements in the table and the index is greater than 0 (that is, the first TR element is removed). We look back at the HTML code, it is not difficult to find that the first TR element is a table header, does not contain any business data, so in the traversal, you should remove this TR element.

4. Recalculate product subtotals and summary information when the user deletes the product or modifies the purchase quantity

Provides a click event for the number adjusted +-number and recalculates the product subtotal/* For each line in the shopping cart, and the input box in each line to bind the keyboard event * perform different actions based on the element that triggered the event * Increase quantity * Decrease quantity * * */$ (carttable). Find ("tr:gt (0)"). each (function () {var input = $ (this). Find (": Text");//Add an event for the Quantity input box,   Calculates the amount subtotal, and updates the total $ (input). KeyUp (function () {var val = parseint ($ (this). Val ()); if (IsNaN (val) | | (Val < 1))    {$ (this). Val ("1");} Getsubtotal (This). Parent (). parent ()); TR element gettotal ();}); /For Quantity adjustment button, delete Add click event, calculate Amount subtotal, and update 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 the "add", "decrease", and "delete" buttons are tied to the event, instead, the Click event is uniformly bound to the TR line, and the element that triggers the Click event is judged to determine what action to take.

When you click on the "+" or "-" button, the program will add or subtract one, and recalculate the subtotal and summary information.

Also, a keyboard event is bound for the quantity input box, which triggers the event every time the keyboard is pressed in the input box, recalculating the product subtotals and summary information.


At this point, the front end of the shopping cart development, is considered to be over.


Shopping Cart front-end development

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.