473,735 Members | 7,637 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SIMPLE Javascript Calculator

Hi,

Firstly, I know NOTHING about Javascript I'm afraid, so I'm hoping that
someone will be able to point me to a ready-made solution to my
problem!

A friend of mine (honest!) is wanting to have on his site, a Javascript
Calculator for working out the cost of what they want, for example:

1 widget and 2 widglets = 5.00
2 widgets and 2 widglets = 7.00

etc etc

He is wanting a solution so that users are faced with two (or maybe
more) drop down boxes where they select how many "widgets" and
"widglets" they want to buy, and the script outputs the price (by
multiplying the two figures).

Can this be done? If so, could someone please kindly supply me with the
script.

TIA, Neil.

Jul 10 '06 #1
24 6339

fi***********@g mail.com писал(а):
Hi,
Firstly, I know NOTHING about Javascript I'm afraid, so I'm hoping that
someone will be able to point me to a ready-made solution to my
problem!
A friend of mine (honest!) is wanting to have on his site, a Javascript
Calculator for working out the cost of what they want, for example:
1 widget and 2 widglets = £5.00
2 widgets and 2 widglets = £7.00
etc etc
He is wanting a solution so that users are faced with two (or maybe
more) drop down boxes where they select how many "widgets" and
"widglets" they want to buy, and the script outputs the price (by
multiplying the two figures).
Can this be done? If so, could someone please kindly supply me with the
script.
TIA, Neil.
------------------------------

Hi,

you can try this:

<html>
<head>
<style type="text/css"><!--
input.num { font-family: monospace; text-align: Right }
h1 {font-family: Comic Sans MS; font-size: 16pt; color: #008080;
font-weight: bold; margin-bottom:0px; padding:0px}
//--></style>
<title>Interact ive JavaScript Order Form</title>
<script language="javas cript"><!--

var RowsInForm = 5 //How many line items will be in the order
form?
var ProductsInList = 10 //How many products in your product list?
var SalesTaxRate = 0.0600 //Set to sales tax rate in decimal. e.g.
0.0775 is 6.00%.
var TaxableState = "FL" //Set to name of state you charge sales tax
in.
var ProdSubscript = 0 //Identifies subscript of selected product
in current row.

function MakeArray(n) {
this.length = n
for (var i=1;i<=n;i++) {this[i]=0}
return this
}

function BuildZeroArray( n) {
this.length = n
for (var i=0;i<=n;i++) {this[i]=0}
return this
}

function prodobj(name, unitprice) {
this.name = name
this.unitprice = unitprice
}

function ordobj(prodsub, qty, unitprice, extprice) {
this.prodsub = prodsub
this.qty = qty
this.unitprice = unitprice
this.extprice = extprice
}

function updateRow(rownu m){
var
exeLine='ProdSu bscript=documen t.ordform.prodc hosen'+rownum+' .selectedIndex'
eval(exeLine)
ordData[rownum].prodsub=ProdSu bscript
var exeLine='tempqt y=document.ordf orm.qty'+rownum +'.value'
eval(exeLine)
ordData[rownum].qty=tempqty-0 //-- Gets unit price from the
product price list.
ordData[rownum].unitprice=prod list[ProdSubscript].unitprice

ordData[rownum].extprice=(ordD ata[rownum].qty)*ordData[rownum].unitprice
var
exeLine='docume nt.ordform.unit price'+rownum+' .value=currency (ordData['+rownum+'].unitprice,10)'
eval (exeLine)
var
exeLine='docume nt.ordform.extp rice'+rownum+'. value=currency( ordData['+rownum+'].extprice,10)'
eval(exeLine)
updateTotals()
}

function updateTotals() {
var subtotal = 0
for (var i=1;i<=RowsInFo rm;i++) {
subtotal=subtot al+ordData[i].extprice
}
document.ordfor m.subtotal.valu e = currency(subtot al,10)
salestax=0
if (document.ordfo rm.Taxable.chec ked) {
salestax = SalesTaxRate*su btotal
}
document.ordfor m.salestax.valu e = currency(salest ax,10)
document.ordfor m.grandtotal.va lue = currency(subtot al+salestax,10)
}

function copyAddress() {
document.ordfor m.shipName.valu e=document.ordf orm.billName.va lue

document.ordfor m.shipCompany.v alue=document.o rdform.billComp any.value
document.ordfor m.shipAdd1.valu e=document.ordf orm.billAdd1.va lue
document.ordfor m.shipAdd2.valu e=document.ordf orm.billAdd2.va lue
document.ordfor m.shipCSZ.value =document.ordfo rm.billCSZ.valu e
document.ordfor m.shipPhone.val ue=document.ord form.billPhone. value
document.ordfor m.shipEmail.val ue=document.ord form.billEmail. value
}

function currency(anynum ,width) {
anynum=eval(any num)
workNum=Math.ab s((Math.round(a nynum*100)/100));workStr=" "+workNum
if (workStr.indexO f(".")==-1){workStr+=".0 0"}
dStr=workStr.su bstr(0,workStr. indexOf("."));d Num=dStr-0
pStr=workStr.su bstr(workStr.in dexOf("."))
while (pStr.length<3) {pStr+="0"}

if (dNum>=1000) {
dLen=dStr.lengt h
dStr=parseInt(" "+(dNum/1000))+","+dStr .substring(dLen-3,dLen)
}

if (dNum>=1000000) {
dLen=dStr.lengt h
dStr=parseInt(" "+(dNum/1000000))+","+d Str.substring(d Len-7,dLen)
}
retval=dStr+pSt r
if (anynum < 0) {
retval=retval.s ubstring(1,retv al.length)
retval="("+retv al+")"
}
retval = "$"+retval
//--Pad with leading blanks to better align numbers.
while (retval.length< width){retval=" "+retval}

return retval
}
//--></script>
</head>
<body>
<CENTER><h2>Int eractive Order Form</h2></CENTER>
<BLOCKQUOTE><BL OCKQUOTE><BLOCK QUOTE>
<p>Here's a hypothetical order form, which uses quite a bit of advanced
JavaScript code. To try it out, pick a product from the drop-down list,
then type in a quantity and click another field, or press Tab. There's
also a button to copy information from the Bill To part of the form to
the Ship To part of the form.
<br></BLOCKQUOTE></BLOCKQUOTE></BLOCKQUOTE><BR>
<script language="JavaS cript"><!--

prodlist = new BuildZeroArray( ProductsInList)

prodlist[0] = new prodobj('-none-',0)
prodlist[1] = new prodobj('Bumper Sticker',10.00)
prodlist[2] = new prodobj('Lapel Pin',10.50)
prodlist[3] = new prodobj('Ball Cap',11.00)
prodlist[4] = new prodobj('Calend ar',11.99)
prodlist[5] = new prodobj('Braide d Ball Cap',12.00)
prodlist[6] = new prodobj('Licens e Plate',14.99)
prodlist[7] = new prodobj('One Year Membership',25. 00)
prodlist[8] = new prodobj('Wrist Watch',99.99)
prodlist[9] = new prodobj('Five Year Membership',100 .00)
prodlist[10] = new prodobj('Life Time Membership',250 .00)

ordData = new MakeArray(RowsI nForm)
for (var i=1; i<= RowsInForm; i++) {
ordData[i] = new ordobj(0,0,0,0)
}
//--></script>
</p>
<form name="ordform" method="POST" action="someHan dler">
<table align="center" border="1" bgcolor="#80000 0"><tr>
<th width="192" BGCOLOR="YELLOW "><b>Produc t</b></th>
<th width="72" BGCOLOR="YELLOW " align="center"> <b>Qty</b></th>
<th width="120" BGCOLOR="YELLOW " align="center"> <b>Unit Price</b></th>
<th width="120" BGCOLOR="YELLOW " align="center"> <b>Ext Price</b></th>
</tr>

<script language="JavaS cript"><!--
for (var rownum=1;rownum <=RowsInForm;ro wnum++) {
document.write( '<tr><td width=192 BGCOLOR="CYAN"> ')
document.write( '<select name="prodchose n'+rownum+'"
onChange="updat eRow('+rownum+' )">')
for (i=0; i<=ProductsInLi st; i++) {
document.write ("<option>"+pro dlist[i].name)
}
document.write ('</select></td>')
document.write ('<td width=72 align="center" BGCOLOR="CYAN"> <input
class="num" name="qty'+rown um+'" value=""')
document.write ('size=3 onChange="updat eRow('+rownum+' )"></td>')
document.write ('<td width=120 align="center" BGCOLOR="CYAN"> ')
document.write ('<input class="num" name="unitprice '+rownum+'"
value="" ')
document.write ('size=10 onfocus="this.b lur()"></td>')
document.write ('<td width=120 align="center" BGCOLOR="CYAN"> ')
document.write ('<input class="num" name="extprice' +rownum+'"
value="" ')
document.write ('size=10 onfocus = "this.blur( )"></td>')
document.write ('</tr>')
}
//--></script>
<tr>
<td width="384" colspan="3" align="right"
BGCOLOR="LIMEGR EEN">Subtotal: </td>
<td width="120" align="center" BGCOLOR="LIMEGR EEN"><input class="num"
name="subtotal" size="10" onfocus="this.b lur()"></td></tr>
<tr><td width="264" colspan="2" BGCOLOR="CYAN"> <input type="checkbox"
name="Taxable" value="true" onclick="update Totals()">Click here if you
live in <script>documen t.write(Taxable State)</script></td>
<td width="120" align="right" BGCOLOR="LIMEGR EEN">Sales Tax:*</td>
<td width="120" align="center" BGCOLOR="CYAN"> <input class="num"
name="salestax" size="10" onfocus="this.b lur()"></td>
</tr>
<tr>
<td width="384" colspan="3" align="right" BGCOLOR="YELLOW ">Grand
Total:</td>
<td width="120" align="center" BGCOLOR="#80000 0"><input class="num"
name="grandtota l" size="10" onfocus="this.b lur()"></td></tr></table>

</body>
</html>
Regards,
Mistral

Jul 10 '06 #2
This looks a little complexfor my needs. If I only have two drop downs
(A & B), how would I do the following:-
Multiply B by 2
Add on A
add on a constants (C) and then output the result to a small read-only
text-box. It can be changed from read-only if necessary.

Regards

Richard

mistral wrote:
fi***********@g mail.com писал(а):
Hi,
Firstly, I know NOTHING about Javascript I'm afraid, so I'm hoping that
someone will be able to point me to a ready-made solution to my
problem!
A friend of mine (honest!) is wanting to have on his site, a Javascript
Calculator for working out the cost of what they want, for example:
1 widget and 2 widglets = £5.00
2 widgets and 2 widglets = £7.00
etc etc
He is wanting a solution so that users are faced with two (or maybe
more) drop down boxes where they select how many "widgets" and
"widglets" they want to buy, and the script outputs the price (by
multiplying the two figures).
Can this be done? If so, could someone please kindly supply me with the
script.
TIA, Neil.
------------------------------

Hi,

you can try this:

<html>
<head>
<style type="text/css"><!--
input.num { font-family: monospace; text-align: Right }
h1 {font-family: Comic Sans MS; font-size: 16pt; color: #008080;
font-weight: bold; margin-bottom:0px; padding:0px}
//--></style>
<title>Interact ive JavaScript Order Form</title>
<script language="javas cript"><!--

var RowsInForm = 5 //How many line items will be in the order
form?
var ProductsInList = 10 //How many products in your product list?
var SalesTaxRate = 0.0600 //Set to sales tax rate in decimal. e.g.
0.0775 is 6.00%.
var TaxableState = "FL" //Set to name of state you charge sales tax
in.
var ProdSubscript = 0 //Identifies subscript of selected product
in current row.

function MakeArray(n) {
this.length = n
for (var i=1;i<=n;i++) {this[i]=0}
return this
}

function BuildZeroArray( n) {
this.length = n
for (var i=0;i<=n;i++) {this[i]=0}
return this
}

function prodobj(name, unitprice) {
this.name = name
this.unitprice = unitprice
}

function ordobj(prodsub, qty, unitprice, extprice) {
this.prodsub = prodsub
this.qty = qty
this.unitprice = unitprice
this.extprice = extprice
}

function updateRow(rownu m){
var
exeLine='ProdSu bscript=documen t.ordform.prodc hosen'+rownum+' .selectedIndex'
eval(exeLine)
ordData[rownum].prodsub=ProdSu bscript
var exeLine='tempqt y=document.ordf orm.qty'+rownum +'.value'
eval(exeLine)
ordData[rownum].qty=tempqty-0 //-- Gets unit price from the
product price list.
ordData[rownum].unitprice=prod list[ProdSubscript].unitprice

ordData[rownum].extprice=(ordD ata[rownum].qty)*ordData[rownum].unitprice
var
exeLine='docume nt.ordform.unit price'+rownum+' .value=currency (ordData['+rownum+'].unitprice,10)'
eval (exeLine)
var
exeLine='docume nt.ordform.extp rice'+rownum+'. value=currency( ordData['+rownum+'].extprice,10)'
eval(exeLine)
updateTotals()
}

function updateTotals() {
var subtotal = 0
for (var i=1;i<=RowsInFo rm;i++) {
subtotal=subtot al+ordData[i].extprice
}
document.ordfor m.subtotal.valu e = currency(subtot al,10)
salestax=0
if (document.ordfo rm.Taxable.chec ked) {
salestax = SalesTaxRate*su btotal
}
document.ordfor m.salestax.valu e = currency(salest ax,10)
document.ordfor m.grandtotal.va lue = currency(subtot al+salestax,10)
}

function copyAddress() {
document.ordfor m.shipName.valu e=document.ordf orm.billName.va lue

document.ordfor m.shipCompany.v alue=document.o rdform.billComp any.value
document.ordfor m.shipAdd1.valu e=document.ordf orm.billAdd1.va lue
document.ordfor m.shipAdd2.valu e=document.ordf orm.billAdd2.va lue
document.ordfor m.shipCSZ.value =document.ordfo rm.billCSZ.valu e
document.ordfor m.shipPhone.val ue=document.ord form.billPhone. value
document.ordfor m.shipEmail.val ue=document.ord form.billEmail. value
}

function currency(anynum ,width) {
anynum=eval(any num)
workNum=Math.ab s((Math.round(a nynum*100)/100));workStr=" "+workNum
if (workStr.indexO f(".")==-1){workStr+=".0 0"}
dStr=workStr.su bstr(0,workStr. indexOf("."));d Num=dStr-0
pStr=workStr.su bstr(workStr.in dexOf("."))
while (pStr.length<3) {pStr+="0"}

if (dNum>=1000) {
dLen=dStr.lengt h
dStr=parseInt(" "+(dNum/1000))+","+dStr .substring(dLen-3,dLen)
}

if (dNum>=1000000) {
dLen=dStr.lengt h
dStr=parseInt(" "+(dNum/1000000))+","+d Str.substring(d Len-7,dLen)
}
retval=dStr+pSt r
if (anynum < 0) {
retval=retval.s ubstring(1,retv al.length)
retval="("+retv al+")"
}
retval = "$"+retval
//--Pad with leading blanks to better align numbers.
while (retval.length< width){retval=" "+retval}

return retval
}
//--></script>
</head>
<body>
<CENTER><h2>Int eractive Order Form</h2></CENTER>
<BLOCKQUOTE><BL OCKQUOTE><BLOCK QUOTE>
<p>Here's a hypothetical order form, which uses quite a bit of advanced
JavaScript code. To try it out, pick a product from the drop-down list,
then type in a quantity and click another field, or press Tab. There's
also a button to copy information from the Bill To part of the form to
the Ship To part of the form.
<br></BLOCKQUOTE></BLOCKQUOTE></BLOCKQUOTE><BR>
<script language="JavaS cript"><!--

prodlist = new BuildZeroArray( ProductsInList)

prodlist[0] = new prodobj('-none-',0)
prodlist[1] = new prodobj('Bumper Sticker',10.00)
prodlist[2] = new prodobj('Lapel Pin',10.50)
prodlist[3] = new prodobj('Ball Cap',11.00)
prodlist[4] = new prodobj('Calend ar',11.99)
prodlist[5] = new prodobj('Braide d Ball Cap',12.00)
prodlist[6] = new prodobj('Licens e Plate',14.99)
prodlist[7] = new prodobj('One Year Membership',25. 00)
prodlist[8] = new prodobj('Wrist Watch',99.99)
prodlist[9] = new prodobj('Five Year Membership',100 .00)
prodlist[10] = new prodobj('Life Time Membership',250 .00)

ordData = new MakeArray(RowsI nForm)
for (var i=1; i<= RowsInForm; i++) {
ordData[i] = new ordobj(0,0,0,0)
}
//--></script>
</p>
<form name="ordform" method="POST" action="someHan dler">
<table align="center" border="1" bgcolor="#80000 0"><tr>
<th width="192" BGCOLOR="YELLOW "><b>Produc t</b></th>
<th width="72" BGCOLOR="YELLOW " align="center"> <b>Qty</b></th>
<th width="120" BGCOLOR="YELLOW " align="center"> <b>Unit Price</b></th>
<th width="120" BGCOLOR="YELLOW " align="center"> <b>Ext Price</b></th>
</tr>

<script language="JavaS cript"><!--
for (var rownum=1;rownum <=RowsInForm;ro wnum++) {
document.write( '<tr><td width=192 BGCOLOR="CYAN"> ')
document.write( '<select name="prodchose n'+rownum+'"
onChange="updat eRow('+rownum+' )">')
for (i=0; i<=ProductsInLi st; i++) {
document.write ("<option>"+pro dlist[i].name)
}
document.write ('</select></td>')
document.write ('<td width=72 align="center" BGCOLOR="CYAN"> <input
class="num" name="qty'+rown um+'" value=""')
document.write ('size=3 onChange="updat eRow('+rownum+' )"></td>')
document.write ('<td width=120 align="center" BGCOLOR="CYAN"> ')
document.write ('<input class="num" name="unitprice '+rownum+'"
value="" ')
document.write ('size=10 onfocus="this.b lur()"></td>')
document.write ('<td width=120 align="center" BGCOLOR="CYAN"> ')
document.write ('<input class="num" name="extprice' +rownum+'"
value="" ')
document.write ('size=10 onfocus = "this.blur( )"></td>')
document.write ('</tr>')
}
//--></script>
<tr>
<td width="384" colspan="3" align="right"
BGCOLOR="LIMEGR EEN">Subtotal: </td>
<td width="120" align="center" BGCOLOR="LIMEGR EEN"><input class="num"
name="subtotal" size="10" onfocus="this.b lur()"></td></tr>
<tr><td width="264" colspan="2" BGCOLOR="CYAN"> <input type="checkbox"
name="Taxable" value="true" onclick="update Totals()">Click here if you
live in <script>documen t.write(Taxable State)</script></td>
<td width="120" align="right" BGCOLOR="LIMEGR EEN">Sales Tax:*</td>
<td width="120" align="center" BGCOLOR="CYAN"> <input class="num"
name="salestax" size="10" onfocus="this.b lur()"></td>
</tr>
<tr>
<td width="384" colspan="3" align="right" BGCOLOR="YELLOW ">Grand
Total:</td>
<td width="120" align="center" BGCOLOR="#80000 0"><input class="num"
name="grandtota l" size="10" onfocus="this.b lur()"></td></tr></table>

</body>
</html>
Regards,
Mistral
Jul 10 '06 #3
JRS: In article <11************ **********@p79g 2000cwp.googleg roups.com>
, dated Mon, 10 Jul 2006 05:46:38 remote, seen in
news:comp.lang. javascript, mistral <po*******@soft home.netposted :
>...
var RowsInForm = 5 //How many line items will be in the order
form?
var ProductsInList = 10 //How many products in your product list?
...
That will not work, because you have posted incompetently.

Especially for readers such as the OP describes himself as, code as
transmitted must be executable code. You have carelessly allowed your
posting agent to line-wrap, making the code non-executable.

If you cannot control your posting agent, then you must write code in
lines which you know to be sufficiently short.

Read the newsgroup FAQ.

Obviously, you have not understood the question. Not only does the OP
write in British English, but he specifically gives prices in pounds
sterling. Therefore, he is rather unlikely to be interested in Florida
sales tax.

In your code, MakeArray(n) and BuildZeroArray( n) should be a single
function (if both effects are really needed) with a parameter for the
starting point; and the setting of .length the same in each case seems
strange.

Function eval is used where it should not be. Much of your code is
weird, irrelevant, or both.

Read the newsgroup FAQ.
===

Lee's code does not work for me - button gives "Object doesn't support
this action", line 14 char 5. I don't see why - the line is
for (item in price) {
But for (var item in price) { works.

I'd write a first column of drop-downs, and a second of item, and a
third of price; I'd just put numbers in the drop-downs, and use
selectedIndex as a multiplier, as Lee does.

For the controlling data structure, I'd consider
var Data = [
{N:7, S:"Thing1", P:5.00},
{N:9, S:"Thing2", P:7.00} ]
where N is the maximum number of S sellable at price P, with code
writing as many rows of input controls as Data has elements, here 2, and
code populating the drop-downs.

--
John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.c om/faq/>? JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 10 '06 #4
Lee

I've just tried your code and got an error on line 16 char 5 - object
doesn't support this property or method.

Also, this is not for emailing anywhere. It will simply be for a web
page so people can work out values before emailing me with other
details.

Regards

Richard

Lee wrote:
richardmgreen said:

This looks a little complexfor my needs. If I only have two drop downs
(A & B), how would I do the following:-
Multiply B by 2
Add on A
add on a constants (C) and then output the result to a small read-only
text-box. It can be changed from read-only if necessary.

There's no real point in making the total read-only. The user can
still change the value before sending it to you, so you absolutely
must recalculate the total price on the server side.
<html>
<head>
<title>Widget Sales</title>
<script type="text/javascript">

var price = { pr_widget : 5.00,
pr_widgelet : 7.00
};
var someConstant=10 ;

function updateTotal(f) {
var total=0;
var itemName;
for (item in price) {
if (itemName=item. match(/pr_(.*)/)) {
itemName=itemNa me[1];
if(f.elements[itemName]) {
total+=f.elemen ts[itemName].selectedIndex* price[item];
}
}
}
if(total>0) {
total+=someCons tant;
}
f.total.value=t otal;
}

</script>
</head>
<body>
<form>
<p>Select the number of each item:</p>
<select name="widget">
<option>No Widgets</option>
<option>One Widget</option>
<option>Two Widget</option>
<option>Three Widget</option>
<option>Four Widget</option>
</select>
<select name="widgelet" >
<option>No Widgelets</option>
<option>One Widgelet</option>
<option>Two Widgelet</option>
<option>Three Widgelet</option>
<option>Four Widgelet</option>
</select>
<br>
<input type="button" value="Update Total" onclick="update Total(this.form )">
<input name="total">
</form>
</body>
</html>
--
Jul 11 '06 #5
Dr John Stockton wrote:
<snip>
Lee's code does not work for me - button gives "Object
doesn't support this action", line 14 char 5. I don't
see why - the line is
for (item in price) {
But for (var item in price) { works.
<snip>

Because IE browsers use the window/global object to implement the -
frames - collection the window/global object has an - item - method.
Without declaring - item - as a global variable the Identifier will be
scope resolved as that - item - method of the global/window object and
as a host provided method it is allowed to be read only, so assignments
to - item - may (and clearly do) error.

Perversely, as it is a method, on IE browsers - typeof item - returns
'string'.

Richard.
Jul 11 '06 #6
In which case, can someone please tell me why thispiece of code isn't
working:-

<script language="text/javascript">
var someConstant=25 ;
function updateTotal(pho tos,videos) {
var total=0;
var photos;
var videos;
totalprice+=(vi deos*2);
totalprice+=pho tos;
if(total>0) {
total+=someCons tant;
}
document.calcul ate.totalprice. value=total;
}
}
</script>

and here's the line that calls the procedure (theoretically) :-
<input value="Get Price"
onclick="update total(numberofp hotos,numberofv ideos)" type="button">

I'm trying to do some paramter passing which is probably where I'm
falling over.

All help gratefully recevied.

Richard
Richard Cornford wrote:
Dr John Stockton wrote:
<snip>
Lee's code does not work for me - button gives "Object
doesn't support this action", line 14 char 5. I don't
see why - the line is
for (item in price) {
But for (var item in price) { works.
<snip>

Because IE browsers use the window/global object to implement the -
frames - collection the window/global object has an - item - method.
Without declaring - item - as a global variable the Identifier will be
scope resolved as that - item - method of the global/window object and
as a host provided method it is allowed to be read only, so assignments
to - item - may (and clearly do) error.

Perversely, as it is a method, on IE browsers - typeof item - returns
'string'.

Richard.
Jul 11 '06 #7
richardmgreen писал(а):
In which case, can someone please tell me why thispiece of code isn't
working:-
<script language="text/javascript">
var someConstant=25 ;
function updateTotal(pho tos,videos) {
var total=0;
var photos;
var videos;
totalprice+=(vi deos*2);
totalprice+=pho tos;
if(total>0) {
total+=someCons tant;
}
document.calcul ate.totalprice. value=total;
}
}
</script>
and here's the line that calls the procedure (theoretically) :-
<input value="Get Price"
onclick="update total(numberofp hotos,numberofv ideos)" type="button">
I'm trying to do some paramter passing which is probably where I'm
falling over.
All help gratefully recevied.
Richard
-------------------------------------------------------------------------

Look at this script instead, simple and convenient - total an Order
Form (a script that totals items using checkboxes and/or select lists).

How to do:
1.Download the script: http://ez-files.net/download.php?file=c4e6799b

2. Include the script. Put the following between the <head></headtags
in your page.
<script type="text/javascript" src="orderform0 3.js"></script>

3. Set up to instantiate an OrderForm object when the page loads.
<script type="text/javascript">
//<![CDATA[
window.onload = setupScripts;
function setupScripts()
{
var anOrder1 = new OrderForm();
}
//]]>
</script>

4. Make sure your html matches the naming conventions in the OrderForm
script, or change the values in the script. You need unique ids for the
form, text output, checkboxes, select lists, and the span tags that
wrap the prices. Here is a simple xhtml example with the default name
formats.
<form id="frmOrder">
<p>
<input type="checkbox" id="chk0" />
Wonder Widget
$<span id="txtPrice0"> 10</span>
<select id="sel0">
<option value="val0">0</option>
<option value="val1">1</option>
<option value="val2">2</option>
<option value="val3">3</option>
</select>
</p>
<p>
<input type="checkbox" id="chk1" />
Snow Widget
$<span id="txtPrice1"> 20</span>
<select id="sel1">
<option value="val0">0</option>
<option value="val1">1</option>
<option value="val2">2</option>
</select>
</p>
<p>
<input type="text" id="txtTotal" size="8" />
</p>
</form>

5. That's all you should need to get it working. Most changes to the
html (such as removing the checkboxes) shouldn't require changes to the
script. Refer to the Notes below for additional tips.

here is script itself:
function OrderForm(prefi x, firstChoice) {

this.prefix = prefix ? prefix : '';

// *************** *************
// Configure here
// *************** *************
// names - Set these according to how the html ids are set
this.FORM_NAME = this.prefix + 'frmOrder';
this.BTN_TOTAL = this.prefix + 'btnTotal';
this.TXT_OUT = this.prefix + 'txtTotal';

// partial names - Set these according to how the html ids are set
this.CHK = this.prefix + 'chk';
this.SEL = this.prefix + 'sel';
this.PRICE = this.prefix + 'txtPrice';

// if the drop down has the first choice after index 1
// this is used when checking or unchecking a checkbox
this.firstChoic e = firstChoice ? firstChoice : 1;
// *************** *************

// form
this.frm = document.getEle mentById(this.F ORM_NAME);

// checkboxes
this.chkReg = new RegExp(this.CHK + '([0-9]+)');
this.getCheck = function(chkId) {
return document.getEle mentById(this.C HK + chkId);
};

// selects
this.selReg = new RegExp(this.SEL + '([0-9]+)');
this.getSelect = function(selId) {
return document.getEle mentById(this.S EL + selId);
};

// price spans
this.priceReg = new RegExp(this.PRI CE + '([0-9]+)');

// text output
this.txtOut = document.getEle mentById(this.T XT_OUT);

// button
this.btnTotal = document.getEle mentById(this.B TN_TOTAL);

// price array
this.prices = new Array();

var o = this;
this.getCheckEv ent = function() {
return function() {
o.checkRetotal( o, this);
};
};

this.getSelectE vent = function() {
return function() {
o.totalCost(o);
};
};

this.getBtnEven t = function() {
return function() {
o.totalCost(o);
};
};

/*
* Calculate the cost
*
* Required:
* Span tags around the prices with IDs formatted
* so each item's numbers correspond its select elements and input
checkboxes.
*/
this.totalCost = function(orderO bj) {
var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
var total = 0.0;
for (var i=0; i<spanObj.lengt h; i++) {
var regResult = orderObj.priceR eg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getChe ck(itemNum);
var selObj = orderObj.getSel ect(itemNum);
var price = orderObj.prices[itemNum];
var quantity = 0;
if (selObj) {
quantity = parseFloat(selO bj.options[selObj.selected Index].text);
quantity = isNaN(quantity) ? 0 : quantity;
if (chkObj) chkObj.checked = quantity;
} else if (chkObj) {
quantity = chkObj.checked ? 1 : 0;
}
total += quantity * price;
}
}
orderObj.txtOut .value = total;
};

/*
* Handle clicks on the checkboxes
*
* Required:
* The corresponding select elements and input checkboxes need to be
numbered the same
*
*/
this.checkRetot al = function(orderO bj, obj) {
var regResult = orderObj.chkReg .exec(obj.id);
if (regResult) {
var optObj = orderObj.getSel ect(regResult[1]);
if (optObj) {
if (obj.checked) {
optObj.selected Index = orderObj.firstC hoice;
} else {
optObj.selected Index = 0;
}
}
orderObj.totalC ost(orderObj);
}
};

/*
* Set up events
*/
this.setEvents = function(orderO bj) {
var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
for (var i=0; i<spanObj.lengt h; i++) {
var regResult = orderObj.priceR eg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getChe ck(itemNum);
var selObj = orderObj.getSel ect(itemNum);
if (chkObj) {
chkObj.onclick = orderObj.getChe ckEvent();
}
if (selObj) {
selObj.onchange = orderObj.getSel ectEvent();
}
if (orderObj.btnTo tal) {
orderObj.btnTot al.onclick = orderObj.getBtn Event();
}
}
}
};
this.setEvents( this);

/*
*
* Grab the prices from the html
* Required:
* Prices should be wrapped in span tags, numbers only.
*/
this.grabPrices = function(orderO bj) {
var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
for (var i=0; i<spanObj.lengt h; i++) {
if (orderObj.price Reg.test(spanOb j[i].id)) {
var regResult = orderObj.priceR eg.exec(spanObj[i].id);
if (regResult) {
orderObj.prices[regResult[1]] = parseFloat(span Obj[i].innerHTML);
}
}
}
};
this.grabPrices (this);

}

Jul 11 '06 #8
Unfortunately, this still looks a little complex for my needs. I
forgot to mention I'm a complete newbie at this and just wanted
something to do a simple calulation, i.e. take two inputs from
drop-down menus (both numeric), do some simple maths as outlined above
and return the result.

mistral wrote:
richardmgreen писал(а):
In which case, can someone please tell me why thispiece of code isn't
working:-

<script language="text/javascript">
var someConstant=25 ;
function updateTotal(pho tos,videos) {
var total=0;
var photos;
var videos;
totalprice+=(vi deos*2);
totalprice+=pho tos;
if(total>0) {
total+=someCons tant;
}
document.calcul ate.totalprice. value=total;
}
}
</script>
and here's the line that calls the procedure (theoretically) :-
<input value="Get Price"
onclick="update total(numberofp hotos,numberofv ideos)" type="button">
I'm trying to do some paramter passing which is probably where I'm
falling over.
All help gratefully recevied.
Richard

-------------------------------------------------------------------------

Look at this script instead, simple and convenient - total an Order
Form (a script that totals items using checkboxes and/or select lists).

How to do:
1.Download the script: http://ez-files.net/download.php?file=c4e6799b

2. Include the script. Put the following between the <head></headtags
in your page.
<script type="text/javascript" src="orderform0 3.js"></script>

3. Set up to instantiate an OrderForm object when the page loads.
<script type="text/javascript">
//<![CDATA[
window.onload = setupScripts;
function setupScripts()
{
var anOrder1 = new OrderForm();
}
//]]>
</script>

4. Make sure your html matches the naming conventions in the OrderForm
script, or change the values in the script. You need unique ids for the
form, text output, checkboxes, select lists, and the span tags that
wrap the prices. Here is a simple xhtml example with the default name
formats.
<form id="frmOrder">
<p>
<input type="checkbox" id="chk0" />
Wonder Widget
$<span id="txtPrice0"> 10</span>
<select id="sel0">
<option value="val0">0</option>
<option value="val1">1</option>
<option value="val2">2</option>
<option value="val3">3</option>
</select>
</p>
<p>
<input type="checkbox" id="chk1" />
Snow Widget
$<span id="txtPrice1"> 20</span>
<select id="sel1">
<option value="val0">0</option>
<option value="val1">1</option>
<option value="val2">2</option>
</select>
</p>
<p>
<input type="text" id="txtTotal" size="8" />
</p>
</form>

5. That's all you should need to get it working. Most changes to the
html (such as removing the checkboxes) shouldn't require changes to the
script. Refer to the Notes below for additional tips.

here is script itself:
function OrderForm(prefi x, firstChoice) {

this.prefix = prefix ? prefix : '';

// *************** *************
// Configure here
// *************** *************
// names - Set these according to how the html ids are set
this.FORM_NAME = this.prefix + 'frmOrder';
this.BTN_TOTAL = this.prefix + 'btnTotal';
this.TXT_OUT = this.prefix + 'txtTotal';

// partial names - Set these according to how the html ids are set
this.CHK = this.prefix + 'chk';
this.SEL = this.prefix + 'sel';
this.PRICE = this.prefix + 'txtPrice';

// if the drop down has the first choice after index 1
// this is used when checking or unchecking a checkbox
this.firstChoic e = firstChoice ? firstChoice : 1;
// *************** *************

// form
this.frm = document.getEle mentById(this.F ORM_NAME);

// checkboxes
this.chkReg = new RegExp(this.CHK + '([0-9]+)');
this.getCheck = function(chkId) {
return document.getEle mentById(this.C HK + chkId);
};

// selects
this.selReg = new RegExp(this.SEL + '([0-9]+)');
this.getSelect = function(selId) {
return document.getEle mentById(this.S EL + selId);
};

// price spans
this.priceReg = new RegExp(this.PRI CE + '([0-9]+)');

// text output
this.txtOut = document.getEle mentById(this.T XT_OUT);

// button
this.btnTotal = document.getEle mentById(this.B TN_TOTAL);

// price array
this.prices = new Array();

var o = this;
this.getCheckEv ent = function() {
return function() {
o.checkRetotal( o, this);
};
};

this.getSelectE vent = function() {
return function() {
o.totalCost(o);
};
};

this.getBtnEven t = function() {
return function() {
o.totalCost(o);
};
};

/*
* Calculate the cost
*
* Required:
* Span tags around the prices with IDs formatted
* so each item's numbers correspond its select elements and input
checkboxes.
*/
this.totalCost = function(orderO bj) {
var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
var total = 0.0;
for (var i=0; i<spanObj.lengt h; i++) {
var regResult = orderObj.priceR eg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getChe ck(itemNum);
var selObj = orderObj.getSel ect(itemNum);
var price = orderObj.prices[itemNum];
var quantity = 0;
if (selObj) {
quantity = parseFloat(selO bj.options[selObj.selected Index].text);
quantity = isNaN(quantity) ? 0 : quantity;
if (chkObj) chkObj.checked = quantity;
} else if (chkObj) {
quantity = chkObj.checked ? 1 : 0;
}
total += quantity * price;
}
}
orderObj.txtOut .value = total;
};

/*
* Handle clicks on the checkboxes
*
* Required:
* The corresponding select elements and input checkboxes need to be
numbered the same
*
*/
this.checkRetot al = function(orderO bj, obj) {
var regResult = orderObj.chkReg .exec(obj.id);
if (regResult) {
var optObj = orderObj.getSel ect(regResult[1]);
if (optObj) {
if (obj.checked) {
optObj.selected Index = orderObj.firstC hoice;
} else {
optObj.selected Index = 0;
}
}
orderObj.totalC ost(orderObj);
}
};

/*
* Set up events
*/
this.setEvents = function(orderO bj) {
var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
for (var i=0; i<spanObj.lengt h; i++) {
var regResult = orderObj.priceR eg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getChe ck(itemNum);
var selObj = orderObj.getSel ect(itemNum);
if (chkObj) {
chkObj.onclick = orderObj.getChe ckEvent();
}
if (selObj) {
selObj.onchange = orderObj.getSel ectEvent();
}
if (orderObj.btnTo tal) {
orderObj.btnTot al.onclick = orderObj.getBtn Event();
}
}
}
};
this.setEvents( this);

/*
*
* Grab the prices from the html
* Required:
* Prices should be wrapped in span tags, numbers only.
*/
this.grabPrices = function(orderO bj) {
var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
for (var i=0; i<spanObj.lengt h; i++) {
if (orderObj.price Reg.test(spanOb j[i].id)) {
var regResult = orderObj.priceR eg.exec(spanObj[i].id);
if (regResult) {
orderObj.prices[regResult[1]] = parseFloat(span Obj[i].innerHTML);
}
}
}
};
this.grabPrices (this);

}
Jul 11 '06 #9
richardmgreen wrote:
In which case, can someone please tell me why thispiece of code
isn't working:-
Whether someone could tell you why your code is 'not working' or not is
only part of your problem. You also have to achieve a situation where
the people who could tell you are willing to try. Presenting your
questions in a normal Usenet post format will help in that direction.
See:-

<URL: http://jibbering.com/faq/ >

<snip>
Richard Cornford wrote:
<snip>

Richard.

Jul 11 '06 #10

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

Similar topics

3
2570
by: Sean McCourt | last post by:
Hi I am doing a JavaScript course and learning from the recommed book (JavaScript 3rd Edition by Don Gosslin) Below is one of the exercises from the book. I get this error message when I try to use the calculator. "document.Calculate.Input is null or not an object" Can someone please tell me why this is?
3
5211
by: Paul | last post by:
I want to make a simple calculator program but dont know where to get started. This is not GUI but a simple terminal program. It would get input like this Enter number: 5 + 10
5
4118
by: VB Programmer | last post by:
I have a javascript calculator. How do I pass the value of the calculator result to another ASPX page so that I can right some VB.NET against the value? Thanks!
14
7474
by: electrician | last post by:
While running a program that exceeds the array limits it issues an alert. I want to then stop the program after filling in the output boxes with blanks. How do you stop the program? I have worked on this for days and tried searching the net, but have found nothing.
3
1678
by: wolis | last post by:
Hi all, In an AJAX environment, is it possible to load and display some HTML and JavaScript and have that JavaScript functional? I have tried but the JavaScript functions dont appear to be visible - Im assuming this is becasue they were not loaded when the initial AJAX application/page originally loaded. Conceptual example if it helps:
1
2938
by: Synapse | last post by:
Hello... We were asked to create a simple calculator program in our C++ subject by using loops only. i have a problem in creating a loop in the multiplication and division operation so please can anyone help me on this please. and also during the operation selection, if ill enter a character it wont go back to the main program. by the way, my compiler is Dev-C++. I need help badly..here's my code below... #include <iostream.h> #include...
1
3333
by: gzeng | last post by:
Hi Everybdy: I am a beginner in C#. I'd like to write a simple online calculator in C#. This calculator will ask a user to input two numbers and then add them and display the result. So, it has two text boxes for a user to input two numbers. It also has a button for the user to get the result after adding these two numbers from input. Can somebody write such a program in C#? I think the program is small. How do I make it online so that...
2
11115
by: masker | last post by:
I was on the web trying to find a javascript that would allow me to input a number on my website and have it increase by a given percentage every second. During my search I found the Earth Population Calculator on the javascripkit.com site. The Calculator functions just as I imagine I want my number generator to function, but I need it to present a different number. I work for a non profit organization that administers Head Start and...
25
5462
by: Oltmans | last post by:
Hi guys, I'm learning JavaScript and I need some puzzles that can make me a better JavaScript programmer. I mean I'm looking out for programming puzzles (e.g. Project Euler or TopCoder) but I'm looking out for language specific puzzles that can make me a top-notch JavaScript programmer. a) Any puzzles you can recommend? b) Any programs that you can suggest that can make me learn JavaScript internals in greatest depth. Please recommend...
0
8785
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9463
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9327
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9200
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6049
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4559
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4822
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3273
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2188
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.