简体   繁体   中英

Calculating the total of an online order form using javascript

I'm working on a basic order form and I would like to see if I can build it from stratch.

I have a form which is made up of a table with 12 items listed and text input fields for item quantity. What I would like to do is have the code run through the form to check for any quantities that have been entered, then relate these values to the prices in an array.

So far I have the array:

var juicePrice = new Array();
juicePrice["citrusZing"]=20.00;
juicePrice["strawberrySmooth"]=22.00;
juicePrice["carrotSpin"]=21.50;
juicePrice["Tropical"]=20.75;
...

and a way to run through the form:

calculateTotal()    
{   
var juiceForm = document.forms["juiceform"];

    //Get a reference to the juice the user Chooses name=selectedJuiceQty":
    var selectedJuiceQty = juiceForm.elements["selectedJuiceQty"];

    for(var i = 0; i < selectedJuiceQty.length; i++);

but I'm not quite sure how to connect the information from the form to calculate the totals. Can anyone point me in the right direction? Is it something like this?

for(var i = 0; i < selectedJuiceQty.length; i++){
    var juiceTotal = 0;

    if(selectedJuiceQty[i]>0) {
        juiceTotal += juicePrice[selectedJuiceQty[i].value]*selectedJuiceQty;
        //If we get a match then we break out of this loop
        break;
    }
    return total;
}

Is it possible to use the same name tag for each field or should I just use citrusZingQty = parseInt(document.getElementById("citrusZing").value); for each item? Then I would have to list all of the items, which doesn't seem a very elegant way. What would happen if multiple items are selected?

Any help anyone can give to point me in the right direction would be great.

So you can do what you want. Michael pointed this out in the comments but it may have been overlooked.

var myPrices = new Object();
myPrices['eggs'] = 1.50;
myPrices['bread'] = 1.00;
// ...

Then you can loop through your form fields and check against your 'myPrices' object.

EDIT

To answer your question in the comments - I would not use the same name for all of my input fields. It does make looping through the form easier perhaps. However, using the id/class of the input tag is not a nice solution in my opinion. HTML id/class are there for CSS/Javascript manipulation and using it to identify which fruit the input represents will not be apparent to other developers working on the project (I realize this may be a small project for you but it's best not to start any bad habits). I would name each input after the juice/drink it represents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM