473,287 Members | 1,419 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,287 software developers and data experts.

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 6258

fi***********@gmail.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>Interactive JavaScript Order Form</title>
<script language="javascript"><!--

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(rownum){
var
exeLine='ProdSubscript=document.ordform.prodchosen '+rownum+'.selectedIndex'
eval(exeLine)
ordData[rownum].prodsub=ProdSubscript
var exeLine='tempqty=document.ordform.qty'+rownum+'.va lue'
eval(exeLine)
ordData[rownum].qty=tempqty-0 //-- Gets unit price from the
product price list.
ordData[rownum].unitprice=prodlist[ProdSubscript].unitprice

ordData[rownum].extprice=(ordData[rownum].qty)*ordData[rownum].unitprice
var
exeLine='document.ordform.unitprice'+rownum+'.valu e=currency(ordData['+rownum+'].unitprice,10)'
eval (exeLine)
var
exeLine='document.ordform.extprice'+rownum+'.value =currency(ordData['+rownum+'].extprice,10)'
eval(exeLine)
updateTotals()
}

function updateTotals() {
var subtotal = 0
for (var i=1;i<=RowsInForm;i++) {
subtotal=subtotal+ordData[i].extprice
}
document.ordform.subtotal.value = currency(subtotal,10)
salestax=0
if (document.ordform.Taxable.checked) {
salestax = SalesTaxRate*subtotal
}
document.ordform.salestax.value = currency(salestax,10)
document.ordform.grandtotal.value = currency(subtotal+salestax,10)
}

function copyAddress() {
document.ordform.shipName.value=document.ordform.b illName.value

document.ordform.shipCompany.value=document.ordfor m.billCompany.value
document.ordform.shipAdd1.value=document.ordform.b illAdd1.value
document.ordform.shipAdd2.value=document.ordform.b illAdd2.value
document.ordform.shipCSZ.value=document.ordform.bi llCSZ.value
document.ordform.shipPhone.value=document.ordform. billPhone.value
document.ordform.shipEmail.value=document.ordform. billEmail.value
}

function currency(anynum,width) {
anynum=eval(anynum)
workNum=Math.abs((Math.round(anynum*100)/100));workStr=""+workNum
if (workStr.indexOf(".")==-1){workStr+=".00"}
dStr=workStr.substr(0,workStr.indexOf("."));dNum=d Str-0
pStr=workStr.substr(workStr.indexOf("."))
while (pStr.length<3){pStr+="0"}

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

if (dNum>=1000000) {
dLen=dStr.length
dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
}
retval=dStr+pStr
if (anynum < 0) {
retval=retval.substring(1,retval.length)
retval="("+retval+")"
}
retval = "$"+retval
//--Pad with leading blanks to better align numbers.
while (retval.length<width){retval=" "+retval}

return retval
}
//--></script>
</head>
<body>
<CENTER><h2>Interactive Order Form</h2></CENTER>
<BLOCKQUOTE><BLOCKQUOTE><BLOCKQUOTE>
<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="JavaScript"><!--

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('Calendar',11.99)
prodlist[5] = new prodobj('Braided Ball Cap',12.00)
prodlist[6] = new prodobj('License 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(RowsInForm)
for (var i=1; i<= RowsInForm; i++) {
ordData[i] = new ordobj(0,0,0,0)
}
//--></script>
</p>
<form name="ordform" method="POST" action="someHandler">
<table align="center" border="1" bgcolor="#800000"><tr>
<th width="192" BGCOLOR="YELLOW"><b>Product</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="JavaScript"><!--
for (var rownum=1;rownum<=RowsInForm;rownum++) {
document.write('<tr><td width=192 BGCOLOR="CYAN">')
document.write('<select name="prodchosen'+rownum+'"
onChange="updateRow('+rownum+')">')
for (i=0; i<=ProductsInList; i++) {
document.write ("<option>"+prodlist[i].name)
}
document.write ('</select></td>')
document.write ('<td width=72 align="center" BGCOLOR="CYAN"><input
class="num" name="qty'+rownum+'" value=""')
document.write ('size=3 onChange="updateRow('+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.blur()"></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="LIMEGREEN">Subtotal:</td>
<td width="120" align="center" BGCOLOR="LIMEGREEN"><input class="num"
name="subtotal" size="10" onfocus="this.blur()"></td></tr>
<tr><td width="264" colspan="2" BGCOLOR="CYAN"><input type="checkbox"
name="Taxable" value="true" onclick="updateTotals()">Click here if you
live in <script>document.write(TaxableState)</script></td>
<td width="120" align="right" BGCOLOR="LIMEGREEN">Sales Tax:Β*</td>
<td width="120" align="center" BGCOLOR="CYAN"><input class="num"
name="salestax" size="10" onfocus="this.blur()"></td>
</tr>
<tr>
<td width="384" colspan="3" align="right" BGCOLOR="YELLOW">Grand
Total:</td>
<td width="120" align="center" BGCOLOR="#800000"><input class="num"
name="grandtotal" size="10" onfocus="this.blur()"></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***********@gmail.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>Interactive JavaScript Order Form</title>
<script language="javascript"><!--

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(rownum){
var
exeLine='ProdSubscript=document.ordform.prodchosen '+rownum+'.selectedIndex'
eval(exeLine)
ordData[rownum].prodsub=ProdSubscript
var exeLine='tempqty=document.ordform.qty'+rownum+'.va lue'
eval(exeLine)
ordData[rownum].qty=tempqty-0 //-- Gets unit price from the
product price list.
ordData[rownum].unitprice=prodlist[ProdSubscript].unitprice

ordData[rownum].extprice=(ordData[rownum].qty)*ordData[rownum].unitprice
var
exeLine='document.ordform.unitprice'+rownum+'.valu e=currency(ordData['+rownum+'].unitprice,10)'
eval (exeLine)
var
exeLine='document.ordform.extprice'+rownum+'.value =currency(ordData['+rownum+'].extprice,10)'
eval(exeLine)
updateTotals()
}

function updateTotals() {
var subtotal = 0
for (var i=1;i<=RowsInForm;i++) {
subtotal=subtotal+ordData[i].extprice
}
document.ordform.subtotal.value = currency(subtotal,10)
salestax=0
if (document.ordform.Taxable.checked) {
salestax = SalesTaxRate*subtotal
}
document.ordform.salestax.value = currency(salestax,10)
document.ordform.grandtotal.value = currency(subtotal+salestax,10)
}

function copyAddress() {
document.ordform.shipName.value=document.ordform.b illName.value

document.ordform.shipCompany.value=document.ordfor m.billCompany.value
document.ordform.shipAdd1.value=document.ordform.b illAdd1.value
document.ordform.shipAdd2.value=document.ordform.b illAdd2.value
document.ordform.shipCSZ.value=document.ordform.bi llCSZ.value
document.ordform.shipPhone.value=document.ordform. billPhone.value
document.ordform.shipEmail.value=document.ordform. billEmail.value
}

function currency(anynum,width) {
anynum=eval(anynum)
workNum=Math.abs((Math.round(anynum*100)/100));workStr=""+workNum
if (workStr.indexOf(".")==-1){workStr+=".00"}
dStr=workStr.substr(0,workStr.indexOf("."));dNum=d Str-0
pStr=workStr.substr(workStr.indexOf("."))
while (pStr.length<3){pStr+="0"}

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

if (dNum>=1000000) {
dLen=dStr.length
dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
}
retval=dStr+pStr
if (anynum < 0) {
retval=retval.substring(1,retval.length)
retval="("+retval+")"
}
retval = "$"+retval
//--Pad with leading blanks to better align numbers.
while (retval.length<width){retval=" "+retval}

return retval
}
//--></script>
</head>
<body>
<CENTER><h2>Interactive Order Form</h2></CENTER>
<BLOCKQUOTE><BLOCKQUOTE><BLOCKQUOTE>
<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="JavaScript"><!--

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('Calendar',11.99)
prodlist[5] = new prodobj('Braided Ball Cap',12.00)
prodlist[6] = new prodobj('License 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(RowsInForm)
for (var i=1; i<= RowsInForm; i++) {
ordData[i] = new ordobj(0,0,0,0)
}
//--></script>
</p>
<form name="ordform" method="POST" action="someHandler">
<table align="center" border="1" bgcolor="#800000"><tr>
<th width="192" BGCOLOR="YELLOW"><b>Product</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="JavaScript"><!--
for (var rownum=1;rownum<=RowsInForm;rownum++) {
document.write('<tr><td width=192 BGCOLOR="CYAN">')
document.write('<select name="prodchosen'+rownum+'"
onChange="updateRow('+rownum+')">')
for (i=0; i<=ProductsInList; i++) {
document.write ("<option>"+prodlist[i].name)
}
document.write ('</select></td>')
document.write ('<td width=72 align="center" BGCOLOR="CYAN"><input
class="num" name="qty'+rownum+'" value=""')
document.write ('size=3 onChange="updateRow('+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.blur()"></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="LIMEGREEN">Subtotal:</td>
<td width="120" align="center" BGCOLOR="LIMEGREEN"><input class="num"
name="subtotal" size="10" onfocus="this.blur()"></td></tr>
<tr><td width="264" colspan="2" BGCOLOR="CYAN"><input type="checkbox"
name="Taxable" value="true" onclick="updateTotals()">Click here if you
live in <script>document.write(TaxableState)</script></td>
<td width="120" align="right" BGCOLOR="LIMEGREEN">Sales Tax:Β*</td>
<td width="120" align="center" BGCOLOR="CYAN"><input class="num"
name="salestax" size="10" onfocus="this.blur()"></td>
</tr>
<tr>
<td width="384" colspan="3" align="right" BGCOLOR="YELLOW">Grand
Total:</td>
<td width="120" align="center" BGCOLOR="#800000"><input class="num"
name="grandtotal" size="10" onfocus="this.blur()"></td></tr></table>

</body>
</html>
Regards,
Mistral
Jul 10 '06 #3
JRS: In article <11**********************@p79g2000cwp.googlegroups .com>
, dated Mon, 10 Jul 2006 05:46:38 remote, seen in
news:comp.lang.javascript, mistral <po*******@softhome.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.com/faq/>? JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.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=itemName[1];
if(f.elements[itemName]) {
total+=f.elements[itemName].selectedIndex*price[item];
}
}
}
if(total>0) {
total+=someConstant;
}
f.total.value=total;
}

</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="updateTotal(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(photos,videos) {
var total=0;
var photos;
var videos;
totalprice+=(videos*2);
totalprice+=photos;
if(total>0) {
total+=someConstant;
}
document.calculate.totalprice.value=total;
}
}
</script>

and here's the line that calls the procedure (theoretically):-
<input value="Get Price"
onclick="updatetotal(numberofphotos,numberofvideos )" 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(photos,videos) {
var total=0;
var photos;
var videos;
totalprice+=(videos*2);
totalprice+=photos;
if(total>0) {
total+=someConstant;
}
document.calculate.totalprice.value=total;
}
}
</script>
and here's the line that calls the procedure (theoretically):-
<input value="Get Price"
onclick="updatetotal(numberofphotos,numberofvideos )" 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="orderform03.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(prefix, 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.firstChoice = firstChoice ? firstChoice : 1;
// ****************************

// form
this.frm = document.getElementById(this.FORM_NAME);

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

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

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

// text output
this.txtOut = document.getElementById(this.TXT_OUT);

// button
this.btnTotal = document.getElementById(this.BTN_TOTAL);

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

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

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

this.getBtnEvent = 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(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
var total = 0.0;
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
var price = orderObj.prices[itemNum];
var quantity = 0;
if (selObj) {
quantity = parseFloat(selObj.options[selObj.selectedIndex].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.checkRetotal = function(orderObj, obj) {
var regResult = orderObj.chkReg.exec(obj.id);
if (regResult) {
var optObj = orderObj.getSelect(regResult[1]);
if (optObj) {
if (obj.checked) {
optObj.selectedIndex = orderObj.firstChoice;
} else {
optObj.selectedIndex = 0;
}
}
orderObj.totalCost(orderObj);
}
};

/*
* Set up events
*/
this.setEvents = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
if (chkObj) {
chkObj.onclick = orderObj.getCheckEvent();
}
if (selObj) {
selObj.onchange = orderObj.getSelectEvent();
}
if (orderObj.btnTotal) {
orderObj.btnTotal.onclick = orderObj.getBtnEvent();
}
}
}
};
this.setEvents(this);

/*
*
* Grab the prices from the html
* Required:
* Prices should be wrapped in span tags, numbers only.
*/
this.grabPrices = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
if (orderObj.priceReg.test(spanObj[i].id)) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
orderObj.prices[regResult[1]] = parseFloat(spanObj[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(photos,videos) {
var total=0;
var photos;
var videos;
totalprice+=(videos*2);
totalprice+=photos;
if(total>0) {
total+=someConstant;
}
document.calculate.totalprice.value=total;
}
}
</script>
and here's the line that calls the procedure (theoretically):-
<input value="Get Price"
onclick="updatetotal(numberofphotos,numberofvideos )" 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="orderform03.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(prefix, 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.firstChoice = firstChoice ? firstChoice : 1;
// ****************************

// form
this.frm = document.getElementById(this.FORM_NAME);

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

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

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

// text output
this.txtOut = document.getElementById(this.TXT_OUT);

// button
this.btnTotal = document.getElementById(this.BTN_TOTAL);

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

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

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

this.getBtnEvent = 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(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
var total = 0.0;
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
var price = orderObj.prices[itemNum];
var quantity = 0;
if (selObj) {
quantity = parseFloat(selObj.options[selObj.selectedIndex].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.checkRetotal = function(orderObj, obj) {
var regResult = orderObj.chkReg.exec(obj.id);
if (regResult) {
var optObj = orderObj.getSelect(regResult[1]);
if (optObj) {
if (obj.checked) {
optObj.selectedIndex = orderObj.firstChoice;
} else {
optObj.selectedIndex = 0;
}
}
orderObj.totalCost(orderObj);
}
};

/*
* Set up events
*/
this.setEvents = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
if (chkObj) {
chkObj.onclick = orderObj.getCheckEvent();
}
if (selObj) {
selObj.onchange = orderObj.getSelectEvent();
}
if (orderObj.btnTotal) {
orderObj.btnTotal.onclick = orderObj.getBtnEvent();
}
}
}
};
this.setEvents(this);

/*
*
* Grab the prices from the html
* Required:
* Prices should be wrapped in span tags, numbers only.
*/
this.grabPrices = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
if (orderObj.priceReg.test(spanObj[i].id)) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
orderObj.prices[regResult[1]] = parseFloat(spanObj[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

richardmgreen писал(а):
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(photos,videos) {
var total=0;
var photos;
var videos;
totalprice+=(videos*2);
totalprice+=photos;
if(total>0) {
total+=someConstant;
}
document.calculate.totalprice.value=total;
}
}
</script>
and here's the line that calls the procedure (theoretically):-
<input value="Get Price"
onclick="updatetotal(numberofphotos,numberofvideos )" 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="orderform03.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(prefix, 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.firstChoice = firstChoice ? firstChoice : 1;
// ****************************

// form
this.frm = document.getElementById(this.FORM_NAME);

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

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

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

// text output
this.txtOut = document.getElementById(this.TXT_OUT);

// button
this.btnTotal = document.getElementById(this.BTN_TOTAL);

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

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

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

this.getBtnEvent = 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(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
var total = 0.0;
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
var price = orderObj.prices[itemNum];
var quantity = 0;
if (selObj) {
quantity = parseFloat(selObj.options[selObj.selectedIndex].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.checkRetotal = function(orderObj, obj) {
var regResult = orderObj.chkReg.exec(obj.id);
if (regResult) {
var optObj = orderObj.getSelect(regResult[1]);
if (optObj) {
if (obj.checked) {
optObj.selectedIndex = orderObj.firstChoice;
} else {
optObj.selectedIndex = 0;
}
}
orderObj.totalCost(orderObj);
}
};

/*
* Set up events
*/
this.setEvents = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
if (chkObj) {
chkObj.onclick = orderObj.getCheckEvent();
}
if (selObj) {
selObj.onchange = orderObj.getSelectEvent();
}
if (orderObj.btnTotal) {
orderObj.btnTotal.onclick = orderObj.getBtnEvent();
}
}
}
};
this.setEvents(this);

/*
*
* Grab the prices from the html
* Required:
* Prices should be wrapped in span tags, numbers only.
*/
this.grabPrices = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
if (orderObj.priceReg.test(spanObj[i].id)) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
orderObj.prices[regResult[1]] = parseFloat(spanObj[i].innerHTML);
}
}
}
};
this.grabPrices(this);

}
----------------------------------------------------

Then you can use this simple form:
<CENTER>
<FONT SIZE=+2 FACE="miffed" COLOR="#0000ff">Javascript Sample Order
Form</FONT>

<FORM NAME="msg">
<UL>
<TABLE CELLPADDING=5>
<TR><TH>Description<TH>Price<TH COLSPAN=2>Order ?

<TR><TD><A HREF="http://www.miffed.com/puzzled/">The Puzzled? CD</A><TD
ALIGN=RIGHT>Ј8.00
<TD><INPUT TYPE="radio" NAME="rad1" VALUE="yes" onclick="if (r1 ==
'off') { r1='on'; distotal(800);}">Yes<TD><INPUT TYPE="radio"
NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
distotal(-800);}"No
<TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј12.00
<TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2 ==
'off') { r2='on'; distotal(1200);}">Yes<TD><INPUT TYPE="radio"
NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
distotal(-1200);}"No
<TR><TD>The Computer game<TD ALIGN=RIGHT>Ј35.00
<TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3 ==
'off') { r3='on'; distotal(3500);} ">Yes<TD><INPUT TYPE="radio"
NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
distotal(-3500);} "No<BR>
<TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј100.00
<TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4 ==
'off') { r4='on'; distotal(10000) ;} ">Yes<TD><INPUT TYPE="radio"
NAME="rad4" CHECKED onclick="if (r4 == 'on') {r4='off';
distotal(-10000); } "No<BR>

<TR><TD ALIGN=RIGHT>Sub Total:<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="sub" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>

<TR><TD ALIGN=RIGHT>+ VAT (17.5% Tax):<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="vat" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>
<TR><TD ALIGN=RIGHT COLSPAN=2>
<FONT SIZE=+2><B>Total: Ј </B></FONT>
<INPUT ALIGN=RIGHT type="text" NAME="tot" VALUE="" SIZE=7
onFocus="this.blur()" ></TD></TABLE>
</UL>

</FORM>

</CENTER>
Rgrds
Mistral

Jul 11 '06 #11
Just tried that and I get an error stating r1 not defined.

Regards

Richard

mistral wrote:
richardmgreen писал(а):
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(photos,videos) {
var total=0;
var photos;
var videos;
totalprice+=(videos*2);
totalprice+=photos;
if(total>0) {
total+=someConstant;
}
document.calculate.totalprice.value=total;
}
}
</script>
>
and here's the line that calls the procedure (theoretically):-
<input value="Get Price"
onclick="updatetotal(numberofphotos,numberofvideos )" 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="orderform03.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(prefix, 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.firstChoice = firstChoice ? firstChoice : 1;
// ****************************
>
// form
this.frm = document.getElementById(this.FORM_NAME);
>
// checkboxes
this.chkReg = new RegExp(this.CHK + '([0-9]+)');
this.getCheck = function(chkId) {
return document.getElementById(this.CHK + chkId);
};
>
// selects
this.selReg = new RegExp(this.SEL + '([0-9]+)');
this.getSelect = function(selId) {
return document.getElementById(this.SEL + selId);
};
>
// price spans
this.priceReg = new RegExp(this.PRICE + '([0-9]+)');
>
// text output
this.txtOut = document.getElementById(this.TXT_OUT);
>
// button
this.btnTotal = document.getElementById(this.BTN_TOTAL);
>
// price array
this.prices = new Array();
>
var o = this;
this.getCheckEvent = function() {
return function() {
o.checkRetotal(o, this);
};
};
>
this.getSelectEvent = function() {
return function() {
o.totalCost(o);
};
};
>
this.getBtnEvent = 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(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
var total = 0.0;
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
var price = orderObj.prices[itemNum];
var quantity = 0;
if (selObj) {
quantity = parseFloat(selObj.options[selObj.selectedIndex].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.checkRetotal = function(orderObj, obj) {
var regResult = orderObj.chkReg.exec(obj.id);
if (regResult) {
var optObj = orderObj.getSelect(regResult[1]);
if (optObj) {
if (obj.checked) {
optObj.selectedIndex = orderObj.firstChoice;
} else {
optObj.selectedIndex = 0;
}
}
orderObj.totalCost(orderObj);
}
};
>
/*
* Set up events
*/
this.setEvents = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
if (chkObj) {
chkObj.onclick = orderObj.getCheckEvent();
}
if (selObj) {
selObj.onchange = orderObj.getSelectEvent();
}
if (orderObj.btnTotal) {
orderObj.btnTotal.onclick = orderObj.getBtnEvent();
}
}
}
};
this.setEvents(this);
>
/*
*
* Grab the prices from the html
* Required:
* Prices should be wrapped in span tags, numbers only.
*/
this.grabPrices = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
if (orderObj.priceReg.test(spanObj[i].id)) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
orderObj.prices[regResult[1]] = parseFloat(spanObj[i].innerHTML);
}
}
}
};
this.grabPrices(this);
>
}

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

Then you can use this simple form:
<CENTER>
<FONT SIZE=+2 FACE="miffed" COLOR="#0000ff">Javascript Sample Order
Form</FONT>

<FORM NAME="msg">
<UL>
<TABLE CELLPADDING=5>
<TR><TH>Description<TH>Price<TH COLSPAN=2>Order ?

<TR><TD><A HREF="http://www.miffed.com/puzzled/">The Puzzled? CD</A><TD
ALIGN=RIGHT>Ј8.00
<TD><INPUT TYPE="radio" NAME="rad1" VALUE="yes" onclick="if (r1 ==
'off') { r1='on'; distotal(800);}">Yes<TD><INPUT TYPE="radio"
NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
distotal(-800);}"No
<TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј12.00
<TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2 ==
'off') { r2='on'; distotal(1200);}">Yes<TD><INPUT TYPE="radio"
NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
distotal(-1200);}"No
<TR><TD>The Computer game<TD ALIGN=RIGHT>Ј35.00
<TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3 ==
'off') { r3='on'; distotal(3500);} ">Yes<TD><INPUT TYPE="radio"
NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
distotal(-3500);} "No<BR>
<TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј100.00
<TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4 ==
'off') { r4='on'; distotal(10000) ;} ">Yes<TD><INPUT TYPE="radio"
NAME="rad4" CHECKED onclick="if (r4 == 'on') {r4='off';
distotal(-10000); } "No<BR>

<TR><TD ALIGN=RIGHT>Sub Total:<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="sub" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>

<TR><TD ALIGN=RIGHT>+ VAT (17.5% Tax):<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="vat" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>
<TR><TD ALIGN=RIGHT COLSPAN=2>
<FONT SIZE=+2><B>Total: Ј </B></FONT>
<INPUT ALIGN=RIGHT type="text" NAME="tot" VALUE="" SIZE=7
onFocus="this.blur()" ></TD></TABLE>
</UL>

</FORM>

</CENTER>
Rgrds
Mistral
Jul 11 '06 #12

richardmgreen писал(а):
Just tried that and I get an error stating r1 not defined.
Regards
Richard
mistral wrote:
richardmgreen писал(а):
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(photos,videos) {
var total=0;
var photos;
var videos;
totalprice+=(videos*2);
totalprice+=photos;
if(total>0) {
total+=someConstant;
}
document.calculate.totalprice.value=total;
}
}
</script>
and here's the line that calls the procedure (theoretically):-
<input value="Get Price"
onclick="updatetotal(numberofphotos,numberofvideos )" 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="orderform03.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 forthe
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 tothe
script. Refer to the Notes below for additional tips.

here is script itself:


function OrderForm(prefix, 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.firstChoice = firstChoice ? firstChoice : 1;
// ****************************

// form
this.frm = document.getElementById(this.FORM_NAME);

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

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

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

// text output
this.txtOut = document.getElementById(this.TXT_OUT);

// button
this.btnTotal = document.getElementById(this.BTN_TOTAL);

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

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

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

this.getBtnEvent = 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(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
var total = 0.0;
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
var price = orderObj.prices[itemNum];
var quantity = 0;
if (selObj) {
quantity = parseFloat(selObj.options[selObj.selectedIndex].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 tobe
numbered the same
*
*/
this.checkRetotal = function(orderObj, obj) {
var regResult = orderObj.chkReg.exec(obj.id);
if (regResult) {
var optObj = orderObj.getSelect(regResult[1]);
if (optObj) {
if (obj.checked) {
optObj.selectedIndex = orderObj.firstChoice;
} else {
optObj.selectedIndex = 0;
}
}
orderObj.totalCost(orderObj);
}
};

/*
* Set up events
*/
this.setEvents = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
if (chkObj) {
chkObj.onclick = orderObj.getCheckEvent();
}
if (selObj) {
selObj.onchange = orderObj.getSelectEvent();
}
if (orderObj.btnTotal) {
orderObj.btnTotal.onclick = orderObj.getBtnEvent();
}
}
}
};
this.setEvents(this);

/*
*
* Grab the prices from the html
* Required:
* Prices should be wrapped in span tags, numbers only.
*/
this.grabPrices = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
if (orderObj.priceReg.test(spanObj[i].id)) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
orderObj.prices[regResult[1]] = parseFloat(spanObj[i].innerHTML);
}
}
}
};
this.grabPrices(this);

}
----------------------------------------------------

Then you can use this simple form:
<CENTER>
<FONT SIZE=+2 FACE="miffed" COLOR="#0000ff">Javascript Sample Order
Form</FONT>

<FORM NAME="msg">
<UL>
<TABLE CELLPADDING=5>
<TR><TH>Description<TH>Price<TH COLSPAN=2>Order ?

<TR><TD><A HREF="http://www.miffed.com/puzzled/">The Puzzled? CD</A><TD
ALIGN=RIGHT>Ј8.00
<TD><INPUT TYPE="radio" NAME="rad1" VALUE="yes" onclick="if (r1==
'off') { r1='on'; distotal(800);}">Yes<TD><INPUT TYPE="radio"
NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
distotal(-800);}"No
<TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј12.00
<TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2==
'off') { r2='on'; distotal(1200);}">Yes<TD><INPUT TYPE="radio"
NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
distotal(-1200);}"No
<TR><TD>The Computer game<TD ALIGN=RIGHT>Ј35.00
<TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3==
'off') { r3='on'; distotal(3500);} ">Yes<TD><INPUT TYPE="radio"
NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
distotal(-3500);} "No<BR>
<TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј100.00
<TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4==
'off') { r4='on'; distotal(10000) ;} ">Yes<TD><INPUT TYPE="radio"
NAME="rad4" CHECKED onclick="if (r4 == 'on') {r4='off';
distotal(-10000); } "No<BR>

<TR><TD ALIGN=RIGHT>Sub Total:<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="sub" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>

<TR><TD ALIGN=RIGHT>+ VAT (17.5% Tax):<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="vat" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>
<TR><TD ALIGN=RIGHT COLSPAN=2>
<FONT SIZE=+2><B>Total: Ј </B></FONT>
<INPUT ALIGN=RIGHT type="text" NAME="tot" VALUE="" SIZE=7
onFocus="this.blur()" ></TD></TABLE>
</UL>

</FORM>

</CENTER>
Rgrds
Mistral
--------------------

sorry, one script part was missed, here you go:

<code>
<HTML>
<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- Beginning of JavaScript Applet -------------------

var sub =0;
var total=0;
var vat=0;
var r1="off";
var r2="off";
var r3="off";
var r4="off";

function distotal(am)
{

total=total+am;
sub=total;
vat=Math.round(sub*0.175);

document.msg.sub.value="Ј"+AddDecimal(sub);
document.msg.vat.value="Ј"+AddDecimal(vat);
document.msg.tot.value=AddDecimal(total+vat);

}

function AddDecimal(number) {
var withdecimal = "";
var num = "" + number;
if (num.length == 0) { withdecimal += "0";
} else if (num.length == 1) { withdecimal += "0.0" + num;
} else if (num.length == 2) { withdecimal += "0." + num;
} else {
withdecimal += num.substring(0, num.length - 2);
withdecimal += "."
withdecimal += num.substring(num.length - 2, num.length);
}
return withdecimal;
}

// -- End of JavaScript code -------------- -->

</SCRIPT>

<TITLE>JavaScript Order Form</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffff" LINK="#0000ff" VLINK="#ff0000">

<CENTER>

<BR><FONT SIZE=+2 FACE="miffed" COLOR="#0000ff">Javascript Sample Order
Form</FONT>

<FORM NAME="msg">
<UL>
<TABLE CELLPADDING=5>
<TR><TH>Description<TH>Price<TH COLSPAN=2>Order ?

<TR><TD><A HREF="http://www.miffed.com/puzzled/">The Puzzled? CD</A><TD
ALIGN=RIGHT>Ј8.00
<TD><INPUT TYPE="radio" NAME="rad1" VALUE="yes" onclick="if (r1 ==
'off') { r1='on'; distotal(800);}">Yes<TD><INPUT TYPE="radio"
NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
distotal(-800);}"No
<TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј12.00
<TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2 ==
'off') { r2='on'; distotal(1200);}">Yes<TD><INPUT TYPE="radio"
NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
distotal(-1200);}"No
<TR><TD>The Computer game<TD ALIGN=RIGHT>Ј35.00
<TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3 ==
'off') { r3='on'; distotal(3500);} ">Yes<TD><INPUT TYPE="radio"
NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
distotal(-3500);} "No<BR>
<TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј100.00
<TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4 ==
'off') { r4='on'; distotal(10000) ;} ">Yes<TD><INPUT TYPE="radio"
NAME="rad4" CHECKED onclick="if (r4 == 'on') {r4='off';
distotal(-10000); } "No<BR>

<TR><TD ALIGN=RIGHT>Sub Total:<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="sub" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>

<TR><TD ALIGN=RIGHT>+ VAT (17.5% Tax):<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="vat" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>
<TR><TD ALIGN=RIGHT COLSPAN=2>
<FONT SIZE=+2><B>Total: Ј </B></FONT>
<INPUT ALIGN=RIGHT type="text" NAME="tot" VALUE="" SIZE=7
onFocus="this.blur()" ></TD></TABLE>
</UL>

</FORM>

</CENTER>

</BODY>
</HTML>
</code>

Mistral

Jul 11 '06 #13
I don't know how much simpler I can make this. This is not the format
I need. It's a basic website, so I want to keep things simple. Select
one value each from two drop-down menus, do some fairly basic maths and
show the result. I don't need check boxes or radio buttons or anything
fancy like a separate line for VAT. I'm simply trying to get a very
basic calculator to work.

Richard

mistral wrote:
richardmgreen писал(а):
Just tried that and I get an error stating r1 not defined.
Regards
Richard

mistral wrote:
richardmgreen писал(а):
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(photos,videos) {
var total=0;
var photos;
var videos;
totalprice+=(videos*2);
totalprice+=photos;
if(total>0) {
total+=someConstant;
}
document.calculate.totalprice.value=total;
}
}
</script>
and here's the line that calls the procedure (theoretically):-
<input value="Get Price"
onclick="updatetotal(numberofphotos,numberofvideos )" 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="orderform03.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(prefix, 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.firstChoice = firstChoice ? firstChoice : 1;
// ****************************
>
// form
this.frm = document.getElementById(this.FORM_NAME);
>
// checkboxes
this.chkReg = new RegExp(this.CHK + '([0-9]+)');
this.getCheck = function(chkId) {
return document.getElementById(this.CHK + chkId);
};
>
// selects
this.selReg = new RegExp(this.SEL + '([0-9]+)');
this.getSelect = function(selId) {
return document.getElementById(this.SEL + selId);
};
>
// price spans
this.priceReg = new RegExp(this.PRICE + '([0-9]+)');
>
// text output
this.txtOut = document.getElementById(this.TXT_OUT);
>
// button
this.btnTotal = document.getElementById(this.BTN_TOTAL);
>
// price array
this.prices = new Array();
>
var o = this;
this.getCheckEvent = function() {
return function() {
o.checkRetotal(o, this);
};
};
>
this.getSelectEvent = function() {
return function() {
o.totalCost(o);
};
};
>
this.getBtnEvent = 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(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
var total = 0.0;
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
var price = orderObj.prices[itemNum];
var quantity = 0;
if (selObj) {
quantity = parseFloat(selObj.options[selObj.selectedIndex]..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.checkRetotal = function(orderObj, obj) {
var regResult = orderObj.chkReg.exec(obj.id);
if (regResult) {
var optObj = orderObj.getSelect(regResult[1]);
if (optObj) {
if (obj.checked) {
optObj.selectedIndex = orderObj.firstChoice;
} else {
optObj.selectedIndex = 0;
}
}
orderObj.totalCost(orderObj);
}
};
>
/*
* Set up events
*/
this.setEvents = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
var itemNum = regResult[1];
var chkObj = orderObj.getCheck(itemNum);
var selObj = orderObj.getSelect(itemNum);
if (chkObj) {
chkObj.onclick = orderObj.getCheckEvent();
}
if (selObj) {
selObj.onchange = orderObj.getSelectEvent();
}
if (orderObj.btnTotal) {
orderObj.btnTotal.onclick = orderObj.getBtnEvent();
}
}
}
};
this.setEvents(this);
>
/*
*
* Grab the prices from the html
* Required:
* Prices should be wrapped in span tags, numbers only.
*/
this.grabPrices = function(orderObj) {
var spanObj = orderObj.frm.getElementsByTagName('span');
for (var i=0; i<spanObj.length; i++) {
if (orderObj.priceReg.test(spanObj[i].id)) {
var regResult = orderObj.priceReg.exec(spanObj[i].id);
if (regResult) {
orderObj.prices[regResult[1]] = parseFloat(spanObj[i].innerHTML);
}
}
}
};
this.grabPrices(this);
>
}
>
----------------------------------------------------
>
Then you can use this simple form:
>
>
<CENTER>
<FONT SIZE=+2 FACE="miffed" COLOR="#0000ff">Javascript Sample Order
Form</FONT>
>
<FORM NAME="msg">
<UL>
<TABLE CELLPADDING=5>
<TR><TH>Description<TH>Price<TH COLSPAN=2>Order ?
>
<TR><TD><A HREF="http://www.miffed.com/puzzled/">The Puzzled? CD</A><TD
ALIGN=RIGHT>Ј8.00
<TD><INPUT TYPE="radio" NAME="rad1" VALUE="yes" onclick="if (r1 ==
'off') { r1='on'; distotal(800);}">Yes<TD><INPUT TYPE="radio"
NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
distotal(-800);}"No
<TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј12.00
<TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2 ==
'off') { r2='on'; distotal(1200);}">Yes<TD><INPUT TYPE="radio"
NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
distotal(-1200);}"No
<TR><TD>The Computer game<TD ALIGN=RIGHT>Ј35.00
<TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3 ==
'off') { r3='on'; distotal(3500);} ">Yes<TD><INPUT TYPE="radio"
NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
distotal(-3500);} "No<BR>
<TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј100.00
<TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4 ==
'off') { r4='on'; distotal(10000) ;} ">Yes<TD><INPUT TYPE="radio"
NAME="rad4" CHECKED onclick="if (r4 == 'on') {r4='off';
distotal(-10000); } "No<BR>
>
<TR><TD ALIGN=RIGHT>Sub Total:<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="sub" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>
>
<TR><TD ALIGN=RIGHT>+ VAT (17.5% Tax):<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="vat" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>
<TR><TD ALIGN=RIGHT COLSPAN=2>
<FONT SIZE=+2><B>Total: Ј </B></FONT>
<INPUT ALIGN=RIGHT type="text" NAME="tot" VALUE="" SIZE=7
onFocus="this.blur()" ></TD></TABLE>
</UL>
>
</FORM>
>
</CENTER>
>
>
Rgrds
Mistral

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

sorry, one script part was missed, here you go:

<code>
<HTML>
<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- Beginning of JavaScript Applet -------------------

var sub =0;
var total=0;
var vat=0;
var r1="off";
var r2="off";
var r3="off";
var r4="off";

function distotal(am)
{

total=total+am;
sub=total;
vat=Math.round(sub*0.175);

document.msg.sub.value="Ј"+AddDecimal(sub);
document.msg.vat.value="Ј"+AddDecimal(vat);
document.msg.tot.value=AddDecimal(total+vat);

}

function AddDecimal(number) {
var withdecimal = "";
var num = "" + number;
if (num.length == 0) { withdecimal += "0";
} else if (num.length == 1) { withdecimal += "0.0" + num;
} else if (num.length == 2) { withdecimal += "0." + num;
} else {
withdecimal += num.substring(0, num.length - 2);
withdecimal += "."
withdecimal += num.substring(num.length - 2, num.length);
}
return withdecimal;
}

// -- End of JavaScript code -------------- -->

</SCRIPT>

<TITLE>JavaScript Order Form</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffff" LINK="#0000ff" VLINK="#ff0000">

<CENTER>

<BR><FONT SIZE=+2 FACE="miffed" COLOR="#0000ff">Javascript Sample Order
Form</FONT>

<FORM NAME="msg">
<UL>
<TABLE CELLPADDING=5>
<TR><TH>Description<TH>Price<TH COLSPAN=2>Order ?

<TR><TD><A HREF="http://www.miffed.com/puzzled/">The Puzzled? CD</A><TD
ALIGN=RIGHT>Ј8.00
<TD><INPUT TYPE="radio" NAME="rad1" VALUE="yes" onclick="if (r1 ==
'off') { r1='on'; distotal(800);}">Yes<TD><INPUT TYPE="radio"
NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
distotal(-800);}"No
<TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј12.00
<TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2 ==
'off') { r2='on'; distotal(1200);}">Yes<TD><INPUT TYPE="radio"
NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
distotal(-1200);}"No
<TR><TD>The Computer game<TD ALIGN=RIGHT>Ј35.00
<TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3 ==
'off') { r3='on'; distotal(3500);} ">Yes<TD><INPUT TYPE="radio"
NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
distotal(-3500);} "No<BR>
<TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј100.00
<TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4 ==
'off') { r4='on'; distotal(10000) ;} ">Yes<TD><INPUT TYPE="radio"
NAME="rad4" CHECKED onclick="if (r4 == 'on') {r4='off';
distotal(-10000); } "No<BR>

<TR><TD ALIGN=RIGHT>Sub Total:<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="sub" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>

<TR><TD ALIGN=RIGHT>+ VAT (17.5% Tax):<TD ALIGN=RIGHT>
<INPUT ALIGN=RIGHT type="text" NAME="vat" VALUE="" SIZE=7
onFocus="this.blur()" ></TD>
<TR><TD ALIGN=RIGHT COLSPAN=2>
<FONT SIZE=+2><B>Total: Ј </B></FONT>
<INPUT ALIGN=RIGHT type="text" NAME="tot" VALUE="" SIZE=7
onFocus="this.blur()" ></TD></TABLE>
</UL>

</FORM>

</CENTER>

</BODY>
</HTML>
</code>

Mistral
Jul 11 '06 #14
<snip... no need to repeat unwanted material ...</snip>

The following consists of two items, calc.htm and calc.js.
You can take out the DOCTYPE statement in the html
to see how Internet Explorer interprets the margin:0px auto;
when in quirks mode. There's a comment in it concerning
class names, where Internet Explorer doesn't accept css
class names starting with an underscore. You can play
with the class name and change it to ._o_s to see what
happens. Change it in the css class definition and in the
one html declaration to see the difference in Internet
Explorer.

I believe it's pretty easy to read and understand. The
onchange event fires when moving out of the changed
item, either by clicking in the other open <input />.

The disabled <inputs /are there to show what goes
into effect when someone types in a different number.

The example can use <selectand <optionitems as
you need. The Calculate() function can then access the
selected item by form.selItem.value or by getting the
index, form.selItem.selectedIndex.

NOTE: Outlook Express breaks up the lines so some
double carriage returns separate the single lined items.
With a quality editor it turns out okay with a few very
long lines.

One thing lacking, involves formatting numbers to two
fixed decimal places. I simply don't understand the sym-
bolic code I found (it all looks worse than assembly
language <gprobably that regular expression syntax
that messes me up).

Feel free to play around with it. If you need some help
converting it to <selectfeel free to ask questions.

Hope this helps.

I'm open to criticisms and suggestions.

--
Jim Carlock
Post replies to the group.

calc.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Giggles And Wiggles</title>
<script type="text/javascript" src="calc.js"></script>
<style type="text/css" media="screen">
h1 { text-align:center; }
input { text-align:right; }
div { vertical-align:middle;line-height:1.5em; }
..d1 { float:left;width:120px;margin:0.2em;text-align:right;clear:none; }
..d2 { float:left;width:300px;margin:0.2em;text-align:left;clear:none; }
..d3 { width:360px;text-align:right;clear:both; }
..dcb { clear:both; }
..dbutt { float:none;width:200px;margin:0px auto;padding:0px;line-height:1.5em; }
/*
* Internet Explorer fails to recognize class names that
* begin with an underscore.
* For Example, "_outer_space", as in:
* ._outer_space { ... }
*/
..o_s { margin:20px;padding:0px; }
/* without the DOCTYPE the margin:auto; fails in Internet Explorer. */
..i_s { float:none;width:436px;margin:auto;padding:0px;cle ar:both;vertical-align:middle; }
</style>
</head>
<body><div class="o_s"><div class="i_s">
<h1>Giggles And Wiggles</h1>
<form name="PriceCalculator" action="">

<div class="dcb"><div class="d1">Giggles Wanted:</div><div class="d2"><input type="text" name="txtGiggleQ" size="4" value="0"
tabindex="1" maxlength="5" onchange="Calculate(this.form)" /<input type="text" name="txtGiggleUnitPrice" disabled="disabled"
value="0.00" title="Giggle Unit Price" size="6" /<input type="text" name="txtGiggleQty" size="4" value="0" disabled="disabled" />
<input type="text" name="txtGiggleTotal" size="5" value="0.00" maxlength="7" disabled="disabled" /></div></div>

<div class="dcb"><div class="d1">Wiggles Wanted:</div><div class="d2"><input type="text" name="txtWiggleQ" size="4" value="0"
tabindex="2" maxlength="5" onchange="Calculate(this.form)" /<input type="text" name="txtWiggleUnitPrice" disabled="disabled"
value="0.00" title="Wiggle Unit Price" size="6" /<input type="text" name="txtWiggleQty" size="4" value="0" disabled="disabled" />
<input type="text" name="txtWiggleTotal" size="5" value="0.00" maxlength="7" disabled="disabled" /></div></div>

<div class="d3">Total Cost: <input type="text" name="txtTotal" disabled="disabled" size="10" value="0.00" maxlength="10" /></div>

<div class="dbutt"><input type="button" style="text-align:center;margin:0.2em;padding:0.20%;width:100p x;border:3px #0066bb outset;"
disabled="disabled" value="Calculate" name="btnSubmit" /></div>

</form></div></div>
</body>
</html>

calc.js

// <!--
// nothing selected upon entry
var iGiggleQty = 0;
var rGigglePrice = 0.00;
var rGiggleTotal = 0.00;
var iWiggleQty = 0;
var rWigglePrice = 0.00;
var rWiggleTotal = 0.00;
var rSubTotal = 0.00;

var aSells = [ // giggles/wiggles qty, price, coupon / discount
[0, 0, 0],
[0, 0, 0]];

var aProducts = [ // product, baseprice, qty1, price1, qty2, price2
["giggle", 11.00, 5, 10.75, 10, 10.25], // giggles
["wiggle", 6.00, 10, 5.50, 20, 4.50] // wiggles
];

function ClearForm(form) {
form.txtGiggleQ.value = "0";
form.txtWiggleQ.value = "0";
form.txtGiggleQty.value = "";
form.txtWiggleQty.value = "";
form.txtGigglePrice.value = "";
form.txtWigglePrice.value = "";
}

function QuantityGiggles(form) {
return(parseInt(form.txtGiggleQ.value));
}

function QuantityWiggles(form) {
return(parseInt(form.txtWiggleQ.value));
}

function Calculate(form) {
iGiggleQty = QuantityGiggles(form);
iWiggleQty = QuantityWiggles(form);
form.txtGiggleQty.value = iGiggleQty;
form.txtWiggleQty.value = iWiggleQty;

if (iGiggleQty aProducts[0, 4]) {
rGigglePrice = aProducts[0][5];
} else if (iGiggleQty aProducts[0][2]) {
rGigglePrice = aProducts[0][3];
} else {
rGigglePrice = aProducts[0][1];
}
form.txtGiggleUnitPrice.value = rGigglePrice;
rGiggleTotal = iGiggleQty * rGigglePrice;

// calculate Wiggles
if (iWiggleQty aProducts[1][4]) {
rWigglePrice = aProducts[1][5];
} else if (iWiggleQty aProducts[1][2]) {
rWigglePrice = aProducts[1][3];
} else {
rWigglePrice = aProducts[1][1];
}
form.txtWiggleUnitPrice.value = rWigglePrice;
rWiggleTotal = iWiggleQty * rWigglePrice;

form.txtGiggleTotal.value = rGiggleTotal;
form.txtWiggleTotal.value = rWiggleTotal;
form.txtTotal.value = rGiggleTotal + rWiggleTotal;
}
// -->

Jul 11 '06 #15
JRS: In article <e8*******************@news.demon.co.uk>, dated Tue, 11
Jul 2006 09:00:55 remote, seen in news:comp.lang.javascript, Richard
Cornford <Ri*****@litotes.demon.co.ukposted :
>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.

That supports the principle that every identifier used within a function
should be declared as a var within that function, or passed in as an
argument, except where it is necessary not to do so.

Also the principle that programmer-introduced identifiers should never
be correctly-spelt (or US-spelt) words - Lee's code works for me when
"item" is changed to "iteem".

Javascript needs an equivalent of VBScript's "Option Explicit".

--
© 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.htmjscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 11 '06 #16
JRS: In article <11*********************@p79g2000cwp.googlegroups. com>,
dated Tue, 11 Jul 2006 02:23:24 remote, seen in
news:comp.lang.javascript, richardmgreen <ri************@tiscali.co.uk>
posted :
>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.
If you read the newsgroup FAQ and start complying with its
recommendations for effective reply formatting - they are fully
compatible with those for the Big-8 newsgroups, and those for news:uk.*
(see sig line 3); you may find that the experts regain some interest in
trying to educate you. If you do not, the programming advice that you
will be offered will come from the less intelligent.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/- FAQish topics, acronyms, & links.
Plaintext, quoting : see <URL:http://www.usenet.org.uk/ukpost.html>
Do not Mail News to me. Before a reply, quote with ">" or "" (SoRFC1036)
Jul 11 '06 #17
fi***********@gmail.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.
---------------------

Here is simple calculator you can use:

<?xml version = "1.0"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
<title>JavaScript Calculator</title>
<script>
var total = 0;
var isNew = true;
var op;

function Calculate()
{
var num = parseInt(document.Calculator.numbers.value);

switch(op)
{
case "plus":
{
total += num;
break;
}
case "minus":
{
total -= num;
break;
}
case "multiply":
{
total *= num;
break;
}
case "divide":
{
total /= num;
break;
}
default:
{
break;
}
}

document.Calculator.numbers.value = total;
}

function SetTotal()
{
Calculate();
total = null;
isNew = true;
}

function SetOperator(setOp)
{
if (total != null)
{
Calculate();
}
else
{
total = parseInt(document.Calculator.numbers.value);
}

op = setOp;
isNew = true;
}

function SetNumber(num)
{
if (isNew == true)
{
document.Calculator.numbers.value = num;
isNew = false;
}
else
{
document.Calculator.numbers.value += num;
}
}

function ClearTotal()
{
total = null;
document.Calculator.numbers.value = "";
isNew = true;
}

function ReturnNumber()
{
window.returnValue = document.Calculator.numbers.value;
}

function CloseCalculator()
{
window.close();
}
</script>

</head>

<body onunload="ReturnNumber();">

<form name="Calculator">

<table width="200">
<tr>
<td colspan="2">
<input type="text" size="27" name="numbers"
style="text-align:right">
</td>
</tr>
<tr>
<td style="width: 155px">
<button style="width:35px; height:35px; font-weight:bold"
name="seven" onclick="SetNumber(7);">7</button>&nbsp;
<button style="width:35px; height:35px; font-weight:bold"
name="eight" onclick="SetNumber(8);">8</button>&nbsp;
<button style="width:35px; height:35px; font-weight:bold"
name="nine" onclick="SetNumber(9);">9</button>&nbsp;
<button style="width:35px; height:35px; font-weight:bold"
name="divide" onclick="SetOperator('divide');">/</button></td>
<td>
<button style="width: 35px; height:35px; font-weight:bold"
name="clear" onclick="ClearTotal();">C</button>
</td>
</tr>
<tr>
<td>
<button style="width:35px; height:35px; font-weight:bold"
name="four" onclick="SetNumber(4);">4</button>&nbsp;
<button style="width:35px; height:35px; font-weight:bold"
name="button" onclick="SetNumber(5);">5</button>&nbsp;
<button style="width:35px; height:35px; font-weight:bold"
name="six" onclick="SetNumber(6);">6</button>&nbsp;
<button style="width:35px; height:35px; font-weight:bold"
name="multiply" onclick="SetOperator('multiply');">*</button>
</td>
<td rowspan="3">
<button style="width: 35px; height:115px; font-weight:bold"
name="equals" onclick="SetTotal();">=</button>
</td>
</tr>
<tr>
<td>
<button style="width:35px; height:35px; font-weight:bold"
name="one" onclick="SetNumber(1);">1</button>&nbsp;
<button style="width:35px; height:35px; font-weight:bold"
name="two" onclick="SetNumber(2);">2</button>&nbsp;
<button style="width:35px; height:35px; font-weight:bold"
name="three" onclick="SetNumber(3);">3</button>&nbsp;
<button style="width:35px; height:35px; font-weight:bold"
name="minus" onclick="SetOperator('minus');">-</button>
</td>
</tr>
<tr>
<td>
<button style="width:113px; height: 35px; font-weight:bold"
name="zero" onclick="SetNumber(0);">0</button>&nbsp;
<button style="width:35px; height:35px; font-weight:bold"
name="plus" onclick="SetOperator('plus');">+</button>
</td>
</tr>
<tr>
<td colspan="2">
<button style="width:192px; height: 35px;" name="close"
onclick="CloseCalculator(0);">Close Calculator</button>
</td>
</tr>
</table>
</form>
</body>

</html>

To use the calculator, copy the abovementioned code and paste it into a
notepad. Save the page as calculator.htm.

Here is page you will call calculator from.

<html>

<head>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252">
<title>Untitled 1</title>
<script>
function OpenCalculator()
{
var ret;
var spanTag;

ret = window.showModalDialog("calculator.htm", "",
"dialogHeight:325px; dialogWidth:215px; resizable:yes;");

spanTag = document.all.tags("span").item("numbers");
spanTag.innerText = ret;
}
</script>
</head>

<body>

<p><a href="javascript:OpenCalculator();">Calculate Numbers</a></p>

<p>The number is: <span id="numbers"></span></p>

</body>

</html>
-----------------------
Mistral

Jul 12 '06 #18
mistral wrote:
<snip>
<?xml version = "1.0"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<snip>
ret = window.showModalDialog("calculator.htm", "",
"dialogHeight:325px; dialogWidth:215px; resizable:yes;");
<snip>

LOL. An XHTML document being written in the most IE dependent was
possible?

Richard.

Jul 12 '06 #19

Richard Cornford писал(а):

mistral wrote:
<snip>
<?xml version = "1.0"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<snip>

ret = window.showModalDialog("calculator.htm", "",
"dialogHeight:325px; dialogWidth:215px; resizable:yes;");
<snip>
LOL. An XHTML document being written in the most IE dependent was
possible?
Richard.
-------------------

Its not really important. Just when use this calculator with the
ShowModalDialog method, we can return a calculated value to the calling
page. Here's how it works: we provide a link to the calculator from a
Web page that references a JavaScript function that uses the
ShowModalDialog method; then when a user closes the calculator, the
total is returned to the first page through the JavaScript function
that called the ShowModalDialog method.

mistral

Jul 12 '06 #20
mistral wrote:
Richard Cornford писал(а):
mistral wrote:
<snip>
<?xml version = "1.0"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<snip>

ret = window.showModalDialog("calculator.htm", "",
"dialogHeight:325px; dialogWidth:215px; resizable:yes;");
<snip>
>LOL. An XHTML document being written in the most IE dependent way
possible?
<snip>
>
Its not really important. Just when use this calculator ... called the
ShowModalDialog method.
That doesn't make using XHTML mark-up exclusively on a browser that can
never interpret it as XHTML any less funny.

Richard.

Jul 12 '06 #21
Richard Cornford said the following on 7/12/2006 7:50 AM:
mistral wrote:
>Richard Cornford писал(а):
mistral wrote:
<snip>
> <?xml version = "1.0"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<snip>

ret = window.showModalDialog("calculator.htm", "",
"dialogHeight:325px; dialogWidth:215px; resizable:yes;");
<snip>
>>LOL. An XHTML document being written in the most IE dependent way
possible?
<snip>
>Its not really important. Just when use this calculator ... called the
ShowModalDialog method.

That doesn't make using XHTML mark-up exclusively on a browser that can
never interpret it as XHTML any less funny.
Hilariously funny at that.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Temporarily at: http://members.aol.com/_ht_a/hikksnotathome/cljfaq/
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jul 12 '06 #22
mistral posted:
<snip>

<?xml version = "1.0"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

</snip>

<snip>
ret = window.showModalDialog("calculator.htm", "",
"dialogHeight:325px; dialogWidth:215px; resizable:yes;");
</snip>
Richard Cornford stated:
LOL. An XHTML document being written in the most IE
dependent way possible?
Richard Cornford grunted:
That doesn't make using XHTML mark-up exclusively on a
browser that can never interpret it as XHTML any less funny.
"Randy Webb" <Hi************@aol.comwrote:
Hilariously funny at that.
I'm interested in the laughs. Do I need to encode Mistral's code
into a document to see it?

--
Jim Carlock
Post replies to the group.
Jul 12 '06 #23
Jim Carlock said the following on 7/12/2006 7:00 PM:
mistral posted:
><snip>

<?xml version = "1.0"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

</snip>

<snip>
ret = window.showModalDialog("calculator.htm", "",
"dialogHeight:325px; dialogWidth:215px; resizable:yes;");
</snip>

Richard Cornford stated:
>LOL. An XHTML document being written in the most IE
dependent way possible?

Richard Cornford grunted:
>That doesn't make using XHTML mark-up exclusively on a
browser that can never interpret it as XHTML any less funny.

"Randy Webb" <Hi************@aol.comwrote:
>Hilariously funny at that.

I'm interested in the laughs. Do I need to encode Mistral's code
into a document to see it?
If you want. But, IE doesn't support xHTML in *any* way even remotely
resembling anything of use. If you server it as text/html then it will
render it as error-corrected tag soup. If you serve it as
application/xhtml+xml then IE prompts with a Save As dialog box.

So, trying to script a document that IE doesn't support using IE only
code is, well, Hilariously funny.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Temporarily at: http://members.aol.com/_ht_a/hikksnotathome/cljfaq/
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Jul 13 '06 #24
Jim Carlock said the following on 7/12/2006 7:00 PM:
I'm interested in the laughs. Do I need to encode Mistral's code
into a document to see it?
"Randy Webb" <Hi************@aol.composted:
IE doesn't support xHTML in *any* way even remotely...
If you serve it as text/html then IE renders it as error-corrected
tag soup. If you serve it as application/xhtml+xml, IE prompts
with a Save As dialog box.
Thanks. The following links helped as well, in case others follow
along.

http://www.xml.com/pub/a/2003/03/19/dive-into-xml.html
http://sastools.com/b2/post/79394232

w3.org provides some help as well.
http://www.w3.org/MarkUp/2004/xhtml-faq

--
Jim Carlock
Post replies to the group.
Jul 13 '06 #25

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

Similar topics

3
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...
3
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
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
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...
3
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...
1
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...
1
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...
2
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...
25
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.