473,406 Members | 2,352 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Calculating shipping cost in a form

I have a form at http://www.develop.check.com.au/hh/order.html where
an extended sub-total and then a grand total is calculated as soon as
a quantity is input by a user. I would like to be able to add the
shipping cost to that grand total.

Shipping costs are in the "Postage & handling charges" link and are a
cost per box. If somebody selects "USA, Canada, Middle East" from the
drop down box it should recalculate the shipping cost, otherwise it
should calculate on the default - Australia.

If I post the calculation functions here they'll wrap but they are at
http://www.develop.check.com.au/hh/calculate2.js

Many TIA for your help.

Jul 23 '05 #1
10 4221
ASM
Howard Martin wrote:
I have a form at http://www.develop.check.com.au/hh/order.html where
an extended sub-total and then a grand total is calculated as soon as
a quantity is input by a user. I would like to be able to add the
shipping cost to that grand total.

Shipping costs are in the "Postage & handling charges" link and are a
cost per box. If somebody selects "USA, Canada, Middle East" from the
drop down box it should recalculate the shipping cost, otherwise it
should calculate on the default - Australia.
calculation in caculate2.js :

shipping = new Array('5.00','7.50','8.50','9.50');

function total(what,number) {
var grandTotal = 0;
var quantTotal = 0;
for (var i=0;i<number;i++) {
if (what.elements['price' + i].value == '')
what.elements['price' + i].value = '0.00'; // fix for Opera.

what.elements['subtotal' + i].value=(what.elements['quantity' + i].value
- 0) * (what.elements['price' + i].value - 0);
if (what.elements['quantity' + i].value == "0")
what.elements['subtotal' + i].value = "0.00";

subtotal=what.elements['subtotal' + i].value
grandTotal += (what.elements['price' + i].value - 0) *
(what.elements['quantity' + i].value - 0);

quantTotal += what.elements['quantity'+i].value*1;
}

shippingCost = quantTotal *
shipping[what.elements['location'].selectedIndex];

shippingCost = quantTotal>200? shippingCost*0.8 :
quantTotal>100? shippingCost*0.9 :
quantTotal>50? shippingCost*0.95 :
shippingCost*1;
grandTotal += shippingCost;

subtotal = roundoff(Math.round(subtotal*Math.pow(10,2))/Math.pow(10,2));
what.grandTotal.value =
roundoff(Math.round(grandTotal*Math.pow(10,2))/Math.pow(10,2));

}
If I post the calculation functions here they'll wrap but they are at
http://www.develop.check.com.au/hh/calculate2.js


calculation here :

shipping = new Array('5.00','7.50','8.50','9.50');

function total2(what) {
var quantTotal = 0;
var j=0;
for(var i=0;i<what.length;i++)
if(what.elements[i].name.substring(0,4)=='quant')
j++;
for (var i=0;i<j;i++)
quantTotal += what.elements['quantity'+i].value*1;
shippingCost = quantTotal *
shipping[what.elements['location'].selectedIndex];
shippingCost = quantTotal>200? shippingCost*0.8 :
quantTotal>100? shippingCost*0.9 :
quantTotal>50? shippingCost*0.95 :
shippingCost*1;
what.grandTotal.value += shippingCost;
what.grandTotal.value=roundoff(Math.round(what.gra ndTotal.value*Math.pow(10,2))/Math.pow(10,2));
}
--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #2
JRS: In article <42*********************@news.wanadoo.fr>, dated Tue,
19 Jul 2005 03:59:12, seen in news:comp.lang.javascript, ASM <stephanemo
ri***********@wanadoo.fr> posted :
Howard Martin wrote:
I have a form at http://www.develop.check.com.au/hh/order.html where
calculation in caculate2.js : grandTotal += (what.elements['price' + i].value - 0) *
(what.elements['quantity' + i].value - 0);
There is no need to explicitly convert String to Number before
multiplication.

quantTotal += what.elements['quantity'+i].value*1;
There is no need to multiply by 1 to convert String to Number; a unary +
does it more elegantly.
See FAQ.

subtotal = roundoff(Math.round(subtotal*Math.pow(10,2))/Math.pow(10,2));
what.grandTotal.value =
roundoff(Math.round(grandTotal*Math.pow(10,2))/Math.pow(10,2));


Math.pow(10, 2) is *always* 100; there is no need to calculate it every
time, or even once. And roundoff is not defined.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #3
ASM
Dr John Stockton wrote:
JRS: In article <42*********************@news.wanadoo.fr>, dated Tue,
19 Jul 2005 03:59:12, seen in news:comp.lang.javascript, ASM <stephanemo
ri***********@wanadoo.fr> posted :
grandTotal += (what.elements['price' + i].value - 0) *
(what.elements['quantity' + i].value - 0);
There is no need to explicitly convert String to Number before
multiplication.


who can do more can do less :-)
quantTotal += what.elements['quantity'+i].value*1;

There is no need to multiply by 1 to convert String to Number; a unary +
does it more elegantly.


not understood what is a unary + ?

foo = foo*1
foo = foo+0
or
foo = Number(foo);

see any really better (or elegant) than other one
See FAQ.


if I find it back
subtotal = roundoff(Math.round(subtotal*Math.pow(10,2))/Math.pow(10,2));
what.grandTotal.value =
roundoff(Math.round(grandTotal*Math.pow(10,2))/Math.pow(10,2));

Math.pow(10, 2) is *always* 100; there is no need to calculate it every
time, or even once. And roundoff is not defined.


I did think this not mine code was debuged ...
and thought it was a hack
in case of famous JS round number = 9.000000000002

--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #4
Dr John Stockton wrote:
JRS: In article <42*********************@news.wanadoo.fr>, dated Tue,
19 Jul 2005 03:59:12, seen in news:comp.lang.javascript, ASM <stephanemo
ri***********@wanadoo.fr> posted :
Howard Martin wrote:
I have a form at http://www.develop.check.com.au/hh/order.html where

calculation in caculate2.js :


grandTotal += (what.elements['price' + i].value - 0) *
(what.elements['quantity' + i].value - 0);

There is no need to explicitly convert String to Number before
multiplication.


And all those 'what.elements' statements can modified for simplicity:

var els = what.elements;

and then:

grandTotal += els['price' + i].value * els['quantity' + i].value;

quantTotal += what.elements['quantity'+i].value*1;

There is no need to multiply by 1 to convert String to Number; a unary +
does it more elegantly.
See FAQ.
subtotal = roundoff(Math.round(subtotal*Math.pow(10,2))/Math.pow(10,2));
what.grandTotal.value =
roundoff(Math.round(grandTotal*Math.pow(10,2))/Math.pow(10,2));

Math.pow(10, 2) is *always* 100; there is no need to calculate it every
time, or even once. And roundoff is not defined.


Roundoff was defined (I missed it too initially)

function roundoff(amount) {
return (amount == Math.floor(amount)) ? amount + '.00' : ( (amount*10 ==
Math.floor(amount*10)) ? amount + '0' : amount);
}

All of the rounding and flooring in other places can be removed and
values 'roundoff-ed' just before display using:

function roundoff(amount) {
x = Math.round(x*100) / 100 + '';
var y = x.split('.');
return ( y.length == 1 )? x+'.00' : ( y[1].length == 2 )? x : x+'0' ;
}

and (for example):

<subtotal_field>.value = roundoff( subtotal );
what.grandTotal.value = roundoff( grandTotal );

Maybe the OP is paid by the metre...

--
Rob
Jul 23 '05 #5
ASM wrote:
Dr John Stockton wrote:
JRS: In article <42*********************@news.wanadoo.fr>, dated Tue,
19 Jul 2005 03:59:12, seen in news:comp.lang.javascript, ASM <stephanemo
ri***********@wanadoo.fr> posted :
grandTotal += (what.elements['price' + i].value - 0) *
(what.elements['quantity' + i].value - 0);

There is no need to explicitly convert String to Number before
multiplication.

who can do more can do less :-)
quantTotal += what.elements['quantity'+i].value*1;


There is no need to multiply by 1 to convert String to Number; a unary +
does it more elegantly.

not understood what is a unary + ?


foo = '10'; // foo is a string
bar = foo + 6; // => bar = 106 --concatenation
bar = +foo + 6; // => bar = 16 --addition
--------^

The unary + converts foo to a number.

foo = foo*1
foo = foo+0
or
foo = Number(foo);

see any really better (or elegant) than other one
See FAQ.

if I find it back
subtotal = roundoff(Math.round(subtotal*Math.pow(10,2))/Math.pow(10,2));
what.grandTotal.value =
roundoff(Math.round(grandTotal*Math.pow(10,2))/Math.pow(10,2));


Math.pow(10, 2) is *always* 100; there is no need to calculate it every
time, or even once. And roundoff is not defined.

I did think this not mine code was debuged ...
and thought it was a hack
in case of famous JS round number = 9.000000000002


The code appears to be to round to 2 decimal places. There are more
efficient ways of doing it (see the FAQ or post above).

<URL:http://www.merlyn.demon.co.uk/js-round.htm#Round>

When working with currency, it is often better to do all calculation in
the minor unit (in this case cents) and only display in major units
(dollars here) at the end. That way, all internal calculations are
simplified.

The OP could do all calculations in whole cents and do entirely integer
arithmetic (there is no division, only integer multiplication and
addition) then just add the decimal place at the very end.

The result is no rounding or flooring anywhere and the final format
thing can be the one posted earlier or if x is zero or greater and does
not have leading zeros:

function format2d ( x ) {
return (x<10)? '0.0'+x : (x<100)? '0.'+x :
x.substring(0,x.length-2) +'.'+ x.substring(x.length-2);
}
--
Rob
Jul 23 '05 #6
On Tue, 19 Jul 2005 03:59:12 +0200, ASM
<st*********************@wanadoo.fr> wrote:
calculation in caculate2.js :

shipping = new Array('5.00','7.50','8.50','9.50');

Many thanks, Stephane. That works very nicely at
http://www.develop.check.com.au/hh/order.html.

The extended subtotal, though, shows as "50" instead of as "50.00".
I've experimented with fixing that but my attempts either make no
difference or break the script!

Howard

Jul 23 '05 #7
On Wed, 20 Jul 2005 01:16:25 GMT, RobG <rg***@iinet.net.auau> wrote:

I have a form at http://www.develop.check.com.au/hh/order.html

var els = what.elements;
<snip>
function roundoff(x) {
x = Math.round(x*100) / 100 + '';
var y = x.split('.');
return ( y.length == 1 )? x+'.00' : ( y[1].length == 2 )? x : x+'0' ;
} Many thanks to all. A combination of the posts has got it working
perfectly though the extended subtotal shows as "50" instead of
"50.00". I've tried to rectify the matter and my feeble attempts are
shown // commented out in
http://www.develop.check.com.au/hh/calculate2.js
and (for example):

<subtotal_field>.value = roundoff( subtotal );
what.grandTotal.value = roundoff( grandTotal );

Maybe the OP is paid by the metre...


Heheh. I wish! The OP is a php bloke who sometimes has to struggle
with JS.

Howard

Jul 23 '05 #8
Howard Martin wrote:
On Wed, 20 Jul 2005 01:16:25 GMT, RobG <rg***@iinet.net.auau> wrote:
I have a form at http://www.develop.check.com.au/hh/order.html

var els = what.elements;

<snip>
function roundoff(x) {
x = Math.round(x*100) / 100 + '';
var y = x.split('.');
return ( y.length == 1 )? x+'.00' : ( y[1].length == 2 )? x : x+'0' ;
}


Many thanks to all. A combination of the posts has got it working
perfectly though the extended subtotal shows as "50" instead of
"50.00". I've tried to rectify the matter and my feeble attempts are
shown // commented out in
http://www.develop.check.com.au/hh/calculate2.js


Comments below...
and (for example):

<subtotal_field>.value = roundoff( subtotal );
what.grandTotal.value = roundoff( grandTotal );

Maybe the OP is paid by the metre...

Heheh. I wish! The OP is a php bloke who sometimes has to struggle
with JS.


Ahh, say no more! ;-p

Your script (I've added quote marks manually):

<!--
Ditch the HTML comments, they are completely unnecessary and possibly
harmful in HTML - and should never be used in a .js file.
function roundoff(amount) {
return (amount == Math.floor(amount)) ? amount + '.00' : ( (amount*10
== Math.floor(amount*10)) ? amount + '0' : amount);
}


Replace this with (one of) the suggested alternatives.
Here is your total() function with the suggested modifications applied.
Using shorter form control names would help too:

function total( what, number ) {

var grandTotal = 0;
var subtotal = 0; // Declare subtotal here
var el = what.elements; // New variable for shorter code

for ( var i=0; i<number; i++ ) {
if ( el['price' + i].value == '') {
el['price' + i].value = '0.00'; // fix for Opera.
}
subtotal = el['quantity'+i].value * el['price'+i].value;
el['subtotal'+i].value = roundoff( subtotal );

grandTotal += subtotal;
}

what.grandTotal.value = roundoff( grandTotal );
}

You don't appear to be doing any input validation (you should be
checking that all input is appropriate numbers). Search the group
archives or read the FAQ, there are plenty of examples.

You should also make all inputs other than quantity 'readonly' so only
the quantity can be changed by the user ( <input type="text" .....
readonly> ) unless you want them messing with the price, etc.

I hope you are validating all input back at the server - your users
could be entering anything and can modify readonly inputs if they want
(most aren't that clever, but they aren't the ones you should be worried
about).

Finally, you should have a 'rest' button on the form - users are much
happier if they can clear all the values if they don't want to continue
with the order.

--
Rob
Jul 23 '05 #9
On Wed, 20 Jul 2005 06:38:17 GMT, RobG <rg***@iinet.net.auau> wrote:

You don't appear to be doing any input validation (you should be
checking that all input is appropriate numbers). Search the group
archives or read the FAQ, there are plenty of examples.

You should also make all inputs other than quantity 'readonly' so only
the quantity can be changed by the user ( <input type="text" .....
readonly> ) unless you want them messing with the price, etc.

I hope you are validating all input back at the server - your users
could be entering anything and can modify readonly inputs if they want
(most aren't that clever, but they aren't the ones you should be worried
about).

Many thanks, Rob. The input validation has been fixed and, yes,
everything will be validated server-side. The URL is now
http://www.develop.check.com.au/hh/order.html
and the JS functions are at
http://www.develop.check.com.au/hh/calculate.js

The lines "I will pay by: Credit card online..." are in fact <SUBMIT>
buttons disguised by the magic of CSS though they don't actually do
anything yet.

Howard

Jul 23 '05 #10
ASM <st*********************@wanadoo.fr> writes:
not understood what is a unary + ?
An unary operator that expects a number and gives the same number
back. It is the dual of the unary negation operator used in, e.g.,
bar = -(a * n + 4);
Like the negation operator, it has the side effect of converting
its argument to a number before acting on it.
foo = foo*1
The multiplication operator converts both its arguments to numbers
before acting on them, so this converts the value of "foo" to a
number and the multiplies it by 1, giving that number.
foo = foo+0
This does not work to convert a string to a numerical value. The
plus operator works both as addition of numbers and concatenation
of strings, and if "foo" contains a string, it will do string
concatenation.
<URL:http://jibbering.com/faq/#FAQ4_21>
or foo = Number(foo);


This is the most direct way of converting a value to a number.
The unary plus opeator would do the same as:

foo = +foo;

Personally, I prefer using the Number function. It might be a
tiny bit slower and a few bytes longer, but it is far more
directly readable, especially to people not as familiar with
Javascript.

I wouldn't worry a miniscule difference in effectivity for
something like string to number conversion. It's not something
that should happen inside a tight loop anyway.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: GB | last post by:
Hi, I'm trying to find an easy, efficient and safe site-to-site backup/failover solution. The idea is to have anytime a remote copy of 99.99% of the data. Productive db -> VPN (internet) ->...
7
by: JLM | last post by:
I have a table that has fieldA, fieldB, fieldC. I want fieldC=fieldA-fieldB. simple enough. the next record I want to be able to do the same on the new value of fieldC. I can do this with SAP...
1
by: webguy262 | last post by:
I'm trying to modify this script... <script language="JavaScript" type="text/javascript"> <!-- /* This script is Copyright (c) Paul McFedries and Logophilia Limited...
33
by: potassium flower | last post by:
I am trying to create a food order system for a restaurant. I have tried using both the DSum and Sum functions to calculate the total cost of an order. The total cost is a textbox on the form...
1
by: mstpaige | last post by:
How do I go about starting to input validation into my form for shipping weight and cost?
2
by: raisq1 | last post by:
I have two tables: Expense Table: ( Contains miscellaneous expenses incurred while the goods are transported ) Expense_Type ContainerID Expense_Dollar Labour 20301 5000.00 ...
1
by: laredotornado | last post by:
Hi, Can anyone recommend a free script for calculating UPS shipping? I am familiar with the script written in 2000 by Jason Costomiris, but UPS is using an XML interface and I wondered if...
4
by: aprillynn82 | last post by:
I can not seem to get the code correct to calculate shipping charges based on weight and distance. The info is: Weight of the Package (in kilograms) / Shipping rate per Mile 2kg or less / $0.01...
2
by: cday119 | last post by:
So I am having a difficult time with some clients. The database is set up like this tblOrder tblOrder_Item_Bridge tblItem internal_id item_id ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.