By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,846 Members | 2,107 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,846 IT Pros & Developers. It's quick & easy.

SIMPLE Javascript Calculator

P: n/a
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
Share this Question
Share on Google+
24 Replies


P: n/a

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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a

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

P: n/a
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

P: n/a

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

P: n/a
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

P: n/a
<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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a

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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
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 discussion thread is closed

Replies have been disabled for this discussion.