Question

i am creating a checkout page where users can purchase goods. i have managed to give each product its price but what I cant do is give them its quantity. i simply do no know how to do it. i created a quantity box for them but i can link the two.

my goal is to update the quantity and total price should be displayed on the checkout form.

since this is my homework for college, this must be done in strictly javascript if a solution arrives.

<script type="text/javascript">
function total(frm) {
    var tot = 0;
    for (var i = 0; i < frm.elements.length; i++) {
        if (frm.elements[i].type == "checkbox") {
            if (frm.elements[i].checked) tot += Number(frm.elements[i].value);
        }
    }
    document.getElementById("totalDiv").firstChild.data = "£" + tot;
    type = "text/javascript" >    total(document.getElementById("theForm"));
}
</script>

<form action="nextpage" method="post" id="theForm">
    <fieldset>
        <legend>Choose your Products</legend>
        <table style="padding:2px">
            <tr>
                <td>
                    <img src="http://placehold.it/200x200" />
                </td>
                <td>
                    <img src="http://placehold.it/200x200" />
                </td>
                <td>
                    <img src="http://placehold.it/200x200" />
                </td>
                <td>
                    <img src="http://placehold.it/200x200" />
                </td>
            </tr>
            <tr>
                <td class="buttons">
                    <div>
                        <input type="checkbox" name="r" value="25" onclick="total(this.form);" />£25</div>
                    <input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
                </td>
                <td class="buttons">
                    <div>
                        <input type="checkbox" name="7" value="50" onclick="total(this.form);" />£50</div>
                    <input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
                </td>
                <td class="buttons">
                    <div>
                        <input type="checkbox" name="asd7" value="75" onclick="total(this.form);" />£75</div>
                    <input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
                </td>
                <td class="buttons">
                    <div>
                        <input type="checkbox" name="rasd7" value="100" onclick="total(this.form);" />£100</div>
                    <input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
                </td>
            </tr>
        </table>
        <div id="totalDiv">&pound;0</div>
        <div>
            <input type="submit" value="Place Order" />
        </div>
    </fieldset>
</form>

http://jsfiddle.net/isherwood/96qkr/

Was it helpful?

Solution

Simple and fast solution

Well the simplest solution would be:

Number(frm.elements[i].value) * Number(frm.elements[i+1].value);

Since the quantity element always comes AFTER the checkbox element.

The JavaScript then becomes:

function total(frm) 
{
    var tot = 0;
    for (var i = 0; i < frm.elements.length; i++) {
        if (frm.elements[i].type == "checkbox") {
            if (frm.elements[i].checked) tot += 
                Number(frm.elements[i].value) * Number(frm.elements[i+1].value);
        }
    }
    document.getElementById("totalDiv").firstChild.data = "£" + tot;
}

You can see this works here.

To guarantee that the total div also gets updated when quantity is changed, you should add the onclick="total(this.form);" event to the class="quantity" input elements as well.

You can see how nicely this works here.

More advanced solution

Personally, I would use tabIndex to group the checkbox and quality inputs.

For example, for the first product:

<td class="buttons">
 <div>
  <input tabindex="1" name="checkbox" type="checkbox" value="25" onclick="total(this.form);"  />£25</div>
  <input tabindex="1" name="quantity" min="0" max="5" type="number" class="quantity" value="1" onclick="total(this.form);"/>
</td>

As you can see, I have explicitly defined the tabIndex and names.

Now for the JavaScript, I now use:

function total(frm) 
{
    var tot         = 0;
    var checkboxes  = document.forms[frm.id].elements["checkbox"];
    var quants      = document.forms[frm.id].elements["quantity"];

    for (var i = 0; i < checkboxes.length; i++) 
    {
        if (checkboxes[i].checked) 
        {
            // if tabIndex correctly specified
            if (checkboxes[i].tabIndex == quants[i].tabIndex)
                // add to total
                tot += Number(checkboxes[i].value) * Number(quants[i].value);
            else
                // notify of bug
                alert('Bug in code: tabIndex of checkbox '+i+' is not the same as tabIndex quantity '+i);
        }
    }
    document.getElementById("totalDiv").firstChild.data = "£" + tot;
}

By doing it this way you get the following advantages:

  • Your HTML code makes more sense (input elements are grouped per tabIndex)
  • Your code is checked for bugs
  • You are absolutely sure that you multiply the correct input elements

You can find this code in this jsFiddle.

Good luck! I hope this helps you out!

Update

To create a sort of checkout system, you could go over all the elements again and store them in a variable.

Then make sure that the form implements a function upon submit:

action="javascript:checkout()"

so in total:

<form action="javascript:checkout()" id="theForm">

Easiest way to create the message would be to use one variable like so:

function checkout()
{
    var message = "";

    var checkboxes  = document.forms["theForm"].elements["checkbox"];
    var quants      = document.forms["theForm"].elements["quantity"];

    for (var i = 0; i < checkboxes.length; i++) 
    {
        if (checkboxes[i].checked) 
        {
            switch(checkboxes[i].tabIndex)
            {
                case 1: message += "iPhone"; break;
                case 2: message += "Screen"; break;
                case 3: message += "Laptop"; break;
                case 4: message += "Coffee"; break;
                default: message += "";
            }

            message += "     Quantity:   " + Number(quants[i].value) + "     Price: £" +                       Number(checkboxes[i].value) * Number(quants[i].value) + "\n";
        }
    }    
    message += "\nTotal:   " + document.getElementById("totalDiv").firstChild.data;

    alert(message);   
}

You can find a working implementation of this here.

Fancy solution

Or if you would like to make it a little bit more fancy, you could do the following:

Add the following HTML:

HTML

<br><br>
<div id="checkout">
    <table id="myTable" border="1">
    <tr>
    <td>Product</td>
    <td>Quantity</td>
    <td>Price</td>
    </tr>
    </table>
</div>

Add the following JavaScript function:

JavaScript

function checkout()
{
    document.getElementById("checkout").innerHTML = '<table id="myTable" border="1"><tr><td><b>Product</b></td><td><b>Quantity</b></td><td><b>Price</b></td></tr></table>';

    // Find a <table> element with id="myTable":
    var table = document.getElementById("myTable");

    var count   = 0;
    var max     = 0;

    var checkboxes  = document.forms["theForm"].elements["checkbox"];
    var quants      = document.forms["theForm"].elements["quantity"];

    for (var i = 0; i < checkboxes.length; i++) 
    {
        if (checkboxes[i].checked) 
        {
            switch(checkboxes[i].tabIndex)
            {
                case 1: message = "iPhone"; break;
                case 2: message = "Screen"; break;
                case 3: message = "Laptop"; break;
                case 4: message = "Coffee"; break;
            }

            count += Number(quants[i].value);
            max   += 1;

            // Create an empty <tr> element and add it to the table:
            var row = table.insertRow(max);

            // Insert new cells (<td> elements) at the 1st, 2nd and 3rd position 
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            var cell3 = row.insertCell(2);

            // Add some text to the new cells:
            cell1.innerHTML = message;
            cell2.innerHTML = Number(quants[i].value); 
            cell3.innerHTML = "£" + Number(checkboxes[i].value) * Number(quants[i].value); 
        }
    }    
        // Calculate total
        var row = table.insertRow(max+1);

        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);

        cell1.innerHTML = "<b>Total</b>";
        cell2.innerHTML = count; 
        cell3.innerHTML = document.getElementById("totalDiv").firstChild.data; 
}

The result looks like this:

enter image description here

You can find the corresponding jsFiddle HERE.

Hope that helps you out!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top