Home > DeveloperSection > Articles > Simple Javascript Practice – Shopping Cart

Simple Javascript Practice – Shopping Cart


JavaScript JavaScript 
Ratings:
0 Comment(s)
 9430  View(s)
Rate this:

Simple Javascript Practice – Shopping Cart

JavaScript (JS) is an open source programming language commonly implemented as part of a web browser in order to create enhanced user interfaces and dynamic websites. Javascript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more.

This tutorial is for those who have some basics of Javascript and HTML and want to extend its javascript knowledge in terms of logic and syntax.

Design the UI in HTML

Before writing the script, first you have to design the user interface. Therefore you have to paste the following given html code in a HTML page.

<body>

    <table border='3' bordercolor='blue' style='left: 50; position: absolute'>

        <tbody>

            <tr>

                <td>

                    <table bgcolor="#E0E0E0" cellpadding='10'>

                        <tr>

                            <td>

                                <label>

                                    Select product:</label>

                            </td>

                            <td>

                                <select name="prn" onchange='showPrice()'>

                                    <option value='select'>---select---</option>

                                    <option value='Laptop'>Laptop</option>

                                    <option value='Palmtop'>Palmtop</option>

                                    <option value='Notebook'>Notebook</option>

                                    <option value='Desktop'>Desktop</option>

                                    <option value='Printer'>Printer</option>

                                </select>

                            </td>

                        </tr>

                        <tr>

                            <td>

                                <label>

                                    Product price:</label>

                            </td>

                            <td>

                                <label id='prp' style='color: blue'>

                                </label>

                            </td>

                        </tr>

                        <tr>

                            <td>

                                <label>

                                    Enter quantity:</label>

                            </td>

                            <td>

                                <input type='text' style='background-color: #E0E0E0' name='prq' disabled size='10'

                                    onkeyup="enable()" />

                            </td>

                        </tr>

                        <tr>

                            <td>

                                <label>

                                    Product cost:</label>

                            </td>

                            <td>

                                <label id='prc' style='color: blue'>

                                </label>

                            </td>

                        </tr>

                        <tr>

                            <td colspan='2' align='center'>

                                <input type='button' name='cc' value='Calculate Cost' disabled onclick='calCost()' />

                            </td>

                        </tr>

                        <tr>

                            <td colspan='2' align='center'>

                                <input type='button' name='addcart' value='Add to Cart' disabled onclick='addToCart()' />

                            </td>

                        </tr>

                    </table>

                </td>

            </tr>

        </tbody>

    </table>

    <table border='3' bordercolor='blue' style='left: 400; position: absolute'>

        <tbody>

            <tr>

                <td>

                    <table bgcolor="#E0E0E0" cellpadding='10'>

                        <tr>

                            <td>

                                <select name='prncart' size='12' onchange="select(this.selectedIndex)" />

                            </td>

                            <td>

                                <select name='prpcart' size='12' onchange="select(this.selectedIndex)" />

                            </td>

                            <td>

                                <select name='prqcart' size='12' onchange="select(this.selectedIndex)" />

                            </td>

                            <td>

                                <select name='prccart' size='12' onchange="select(this.selectedIndex)" />

                            </td>

                        </tr>

                        <tr>

                            <td colspan='4' align='right'>

                                <label>

                                    Payable amount:</label>

                                <label id='pa' style='color: blue'>

                                    Rs:0</label>

                            </td>

                        </tr>

                        <tr>

                            <td colspan='4' align='center'>

                                <input type='button' value='Remove product' disabled name="rp" onclick="remProduct()" />

                            </td>

                        </tr>

                    </table>

                </td>

            </tr>

        </tbody>

    </table>

</body>

 

The design will look like below figure:

Simple Javascript Practice – Shopping Cart

Javascript functions

showPrice(): This function have some predefined list of price in array (price) and on the change of product dropdown display the price on the basis dropdown selected index.

function showPrice() {

            var price = ["", "35000", "20000", "18900", "25000", "9000"];

            var i = document.getElementById("prn").selectedIndex;

            if (i != 0) {

                document.getElementById("prp").innerHTML = "Rs:" + price[i];

                document.getElementById("prq").disabled = false;

                document.getElementById("prq").style.backgroundColor = "white";

                document.getElementById("prq").focus();

            }

        }

Simple Javascript Practice – Shopping Cart

enable(): This function will enable the Calculate Cost button if the valid value is entered by the User in the quantity textbox. Valid value criteria are textbox must not be left blank and must be a positive integer.

function enable() {

            var str = document.getElementById("prq").value;

            if (str != "" && !isNaN(str) && str != "0")

                document.getElementById("cc").disabled = false;

            else

                document.getElementById("cc").disabled = true;

        }

 

calCost():This function multiply the quantity with the price and display the product cost.

function calCost()//function to calculate the cost of the product

        {

            var pr = document.getElementById("prp").innerHTML;

            pr = parseInt(pr.substring(3));

            var qt = parseInt(document.getElementById("prq").value);

            document.getElementById("prc").innerHTML = "Rs:" + (pr * qt);

            document.getElementById("addcart").disabled = false;

        }

 

Simple Javascript Practice – Shopping Cart

conv(pr): This function return integer value after removing alphabets through substring. For ex: If we pass “Rs.70000” as parameter then it will return 70000.

function conv(pr) {

            pr = parseInt(pr.substring(3));

            return pr;

        }

 

indexOf(prn): This function will return -1 if the product is not find in the cart otherwise return index from the listbox.

function indexOf(prn) {

            var i = -1;

            for (c = 0; c < document.getElementById("prncart").length; c++) {

                var cv = document.getElementById("prncart").options[c].value;

                if (prn == cv) {

                    i = c;

                    break;

                }

            }

            return i;

        }

 

disable(): This function will reset the form value as display in the load time.

function disable() {

            document.getElementById("prn").selectedIndex = 0;

            document.getElementById("prp").innerHTML = "";

            document.getElementById("prq").value = "";

            document.getElementById("prq").disabled = true;

            document.getElementById("prq").style.backgroundColor = "#E0E0E0";

            document.getElementById("prc").innerHTML = "";

            document.getElementById("cc").disabled = true;

            document.getElementById("addcart").disabled = true;

        }

 

addToCart(): This function add the product in cart boxes. First it check’s whether product exist in the cart by using indexOf(prn) function, if -1 is found it will add the product otherwise update quantity and price  and it also uses conv(pr) function to parse the price value to int. After adding or updating the product it reset the form fields by using disable() function.

function addToCart() {

            var i = indexOf(document.getElementById("prn").value);

            if (i == -1) {

                var opt = document.createElement("option");

                opt.value = document.getElementById("prn").value;

                opt.text = document.getElementById("prn").value;

                document.getElementById("prncart").options.add(opt);

 

                opt = document.createElement("option");

                opt.value = document.getElementById("prp").innerHTML

                opt.text = document.getElementById("prp").innerHTML

                document.getElementById("prpcart").options.add(opt);

 

                opt = document.createElement("option");

                opt.value = document.getElementById("prq").value;

                opt.text = document.getElementById("prq").value;

                document.getElementById("prqcart").options.add(opt);

 

                opt = document.createElement("option");

                opt.value = document.getElementById("prc").innerHTML;

                opt.text = document.getElementById("prc").innerHTML;

                document.getElementById("prccart").options.add(opt);

            }

            else {

                var cq = parseInt(document.getElementById("prqcart").options[i].value);

                var nq = parseInt(document.getElementById("prq").value);

                document.getElementById("prqcart").options[i].value = cq + nq;

                document.getElementById("prqcart").options[i].text = cq + nq;

 

                var cc = conv(document.getElementById("prccart").options[i].value);

                var nc = conv(document.getElementById("prc").innerHTML);

                document.getElementById("prccart").options[i].value = "Rs:" + (cc + nc);

                document.getElementById("prccart").options[i].text = "Rs:" + (cc + nc);

            }

            var pav = conv(document.getElementById("pa").innerHTML);

            var prcv = conv(document.getElementById("prc").innerHTML);

            document.getElementById("pa").innerHTML = "Rs:" + (pav + prcv);

            document.getElementById("rp").disabled = false;

            disable();

        }

Simple Javascript Practice – Shopping Cart

select(i):This function selects all the listbox whenever one of the litbox is select by the user.

function select(i) {

            document.getElementById("prncart").selectedIndex = i;

            document.getElementById("prpcart").selectedIndex = i;

            document.getElementById("prccart").selectedIndex = i;

            document.getElementById("prqcart").selectedIndex = i;

        }

 

remProduct():This function remove the product from the cart and update the Payable amount in the cart.

function remProduct() {

            var i = document.getElementById("prncart").selectedIndex;

            if (i == -1)

                alert("Please select the product");

            else {

                document.getElementById("prncart").remove(i);

                document.getElementById("prpcart").remove(i);

                document.getElementById("prqcart").remove(i);

                var lp = conv(document.getElementById("prccart").options[i].value);

                document.getElementById("prccart").remove(i);

 

                if (document.getElementById("prncart").length == 0)

                    document.getElementById("rp").disabled = true;

                else

                    document.getElementById("rp").disabled = false;

                var na = conv(document.getElementById("pa").innerHTML);

                document.getElementById("pa").innerHTML = "Rs:" + (na - lp);

            }

        }           

 

Simple Javascript Practice – Shopping Cart

Thanks for reading this article. I think this will helps you a lot.


Don't want to miss updates? Please click the below button!

Follow MindStick