SIMPLE Javascript Calculator

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • firstcustomer@gmail.com

    SIMPLE Javascript Calculator

    Hi,

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

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

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

    etc etc

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

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

    TIA, Neil.

  • mistral

    #2
    Re: SIMPLE Javascript Calculator


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

    Hi,

    you can try this:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    prodlist = new BuildZeroArray( ProductsInList)

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

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

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

    </body>
    </html>


    Regards,
    Mistral

    Comment

    • richardmgreen

      #3
      Re: SIMPLE Javascript Calculator

      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:
      firstcustomer@g mail.com писал(а):
      >
      Hi,
      >
      Firstly, I know NOTHING about Javascript I'm afraid, so I'm hoping that
      someone will be able to point me to a ready-made solution to my
      problem!
      >
      A friend of mine (honest!) is wanting to have on his site, a Javascript
      Calculator for working out the cost of what they want, for example:
      >
      1 widget and 2 widglets = £5.00
      2 widgets and 2 widglets = £7.00
      >
      etc etc
      >
      He is wanting a solution so that users are faced with two (or maybe
      more) drop down boxes where they select how many "widgets" and
      "widglets" they want to buy, and the script outputs the price (by
      multiplying the two figures).
      >
      Can this be done? If so, could someone please kindly supply me with the
      script.
      >
      TIA, Neil.
      ------------------------------
      >
      Hi,
      >
      you can try this:
      >
      <html>
      <head>
      <style type="text/css"><!--
      input.num { font-family: monospace; text-align: Right }
      h1 {font-family: Comic Sans MS; font-size: 16pt; color: #008080;
      font-weight: bold; margin-bottom:0px; padding:0px}
      //--></style>
      <title>Interact ive JavaScript Order Form</title>
      <script language="javas cript"><!--
      >
      var RowsInForm = 5 //How many line items will be in the order
      form?
      var ProductsInList = 10 //How many products in your product list?
      var SalesTaxRate = 0.0600 //Set to sales tax rate in decimal. e.g.
      0.0775 is 6.00%.
      var TaxableState = "FL" //Set to name of state you charge sales tax
      in.
      var ProdSubscript = 0 //Identifies subscript of selected product
      in current row.
      >
      function MakeArray(n) {
      this.length = n
      for (var i=1;i<=n;i++) {this[i]=0}
      return this
      }
      >
      function BuildZeroArray( n) {
      this.length = n
      for (var i=0;i<=n;i++) {this[i]=0}
      return this
      }
      >
      function prodobj(name, unitprice) {
      this.name = name
      this.unitprice = unitprice
      }
      >
      function ordobj(prodsub, qty, unitprice, extprice) {
      this.prodsub = prodsub
      this.qty = qty
      this.unitprice = unitprice
      this.extprice = extprice
      }
      >
      function updateRow(rownu m){
      var
      exeLine='ProdSu bscript=documen t.ordform.prodc hosen'+rownum+' .selectedIndex'
      eval(exeLine)
      ordData[rownum].prodsub=ProdSu bscript
      var exeLine='tempqt y=document.ordf orm.qty'+rownum +'.value'
      eval(exeLine)
      ordData[rownum].qty=tempqty-0 //-- Gets unit price from the
      product price list.
      ordData[rownum].unitprice=prod list[ProdSubscript].unitprice
      >
      ordData[rownum].extprice=(ordD ata[rownum].qty)*ordData[rownum].unitprice
      var
      exeLine='docume nt.ordform.unit price'+rownum+' .value=currency (ordData['+rownum+'].unitprice,10)'
      eval (exeLine)
      var
      exeLine='docume nt.ordform.extp rice'+rownum+'. value=currency( ordData['+rownum+'].extprice,10)'
      eval(exeLine)
      updateTotals()
      }
      >
      function updateTotals() {
      var subtotal = 0
      for (var i=1;i<=RowsInFo rm;i++) {
      subtotal=subtot al+ordData[i].extprice
      }
      document.ordfor m.subtotal.valu e = currency(subtot al,10)
      salestax=0
      if (document.ordfo rm.Taxable.chec ked) {
      salestax = SalesTaxRate*su btotal
      }
      document.ordfor m.salestax.valu e = currency(salest ax,10)
      document.ordfor m.grandtotal.va lue = currency(subtot al+salestax,10)
      }
      >
      function copyAddress() {
      document.ordfor m.shipName.valu e=document.ordf orm.billName.va lue
      >
      document.ordfor m.shipCompany.v alue=document.o rdform.billComp any.value
      document.ordfor m.shipAdd1.valu e=document.ordf orm.billAdd1.va lue
      document.ordfor m.shipAdd2.valu e=document.ordf orm.billAdd2.va lue
      document.ordfor m.shipCSZ.value =document.ordfo rm.billCSZ.valu e
      document.ordfor m.shipPhone.val ue=document.ord form.billPhone. value
      document.ordfor m.shipEmail.val ue=document.ord form.billEmail. value
      }
      >
      function currency(anynum ,width) {
      anynum=eval(any num)
      workNum=Math.ab s((Math.round(a nynum*100)/100));workStr=" "+workNum
      if (workStr.indexO f(".")==-1){workStr+=".0 0"}
      dStr=workStr.su bstr(0,workStr. indexOf("."));d Num=dStr-0
      pStr=workStr.su bstr(workStr.in dexOf("."))
      while (pStr.length<3) {pStr+="0"}
      >
      if (dNum>=1000) {
      dLen=dStr.lengt h
      dStr=parseInt(" "+(dNum/1000))+","+dStr .substring(dLen-3,dLen)
      }
      >
      if (dNum>=1000000) {
      dLen=dStr.lengt h
      dStr=parseInt(" "+(dNum/1000000))+","+d Str.substring(d Len-7,dLen)
      }
      retval=dStr+pSt r
      if (anynum < 0) {
      retval=retval.s ubstring(1,retv al.length)
      retval="("+retv al+")"
      }
      retval = "$"+retval
      //--Pad with leading blanks to better align numbers.
      while (retval.length< width){retval=" "+retval}
      >
      return retval
      }
      //--></script>
      </head>
      <body>
      <CENTER><h2>Int eractive Order Form</h2></CENTER>
      <BLOCKQUOTE><BL OCKQUOTE><BLOCK QUOTE>
      <p>Here's a hypothetical order form, which uses quite a bit of advanced
      JavaScript code. To try it out, pick a product from the drop-down list,
      then type in a quantity and click another field, or press Tab. There's
      also a button to copy information from the Bill To part of the form to
      the Ship To part of the form.
      <br></BLOCKQUOTE></BLOCKQUOTE></BLOCKQUOTE><BR>
      <script language="JavaS cript"><!--
      >
      prodlist = new BuildZeroArray( ProductsInList)
      >
      prodlist[0] = new prodobj('-none-',0)
      prodlist[1] = new prodobj('Bumper Sticker',10.00)
      prodlist[2] = new prodobj('Lapel Pin',10.50)
      prodlist[3] = new prodobj('Ball Cap',11.00)
      prodlist[4] = new prodobj('Calend ar',11.99)
      prodlist[5] = new prodobj('Braide d Ball Cap',12.00)
      prodlist[6] = new prodobj('Licens e Plate',14.99)
      prodlist[7] = new prodobj('One Year Membership',25. 00)
      prodlist[8] = new prodobj('Wrist Watch',99.99)
      prodlist[9] = new prodobj('Five Year Membership',100 .00)
      prodlist[10] = new prodobj('Life Time Membership',250 .00)
      >
      ordData = new MakeArray(RowsI nForm)
      for (var i=1; i<= RowsInForm; i++) {
      ordData[i] = new ordobj(0,0,0,0)
      }
      //--></script>
      </p>
      <form name="ordform" method="POST" action="someHan dler">
      <table align="center" border="1" bgcolor="#80000 0"><tr>
      <th width="192" BGCOLOR="YELLOW "><b>Produc t</b></th>
      <th width="72" BGCOLOR="YELLOW " align="center"> <b>Qty</b></th>
      <th width="120" BGCOLOR="YELLOW " align="center"> <b>Unit Price</b></th>
      <th width="120" BGCOLOR="YELLOW " align="center"> <b>Ext Price</b></th>
      </tr>
      >
      <script language="JavaS cript"><!--
      for (var rownum=1;rownum <=RowsInForm;ro wnum++) {
      document.write( '<tr><td width=192 BGCOLOR="CYAN"> ')
      document.write( '<select name="prodchose n'+rownum+'"
      onChange="updat eRow('+rownum+' )">')
      for (i=0; i<=ProductsInLi st; i++) {
      document.write ("<option>"+pro dlist[i].name)
      }
      document.write ('</select></td>')
      document.write ('<td width=72 align="center" BGCOLOR="CYAN"> <input
      class="num" name="qty'+rown um+'" value=""')
      document.write ('size=3 onChange="updat eRow('+rownum+' )"></td>')
      document.write ('<td width=120 align="center" BGCOLOR="CYAN"> ')
      document.write ('<input class="num" name="unitprice '+rownum+'"
      value="" ')
      document.write ('size=10 onfocus="this.b lur()"></td>')
      document.write ('<td width=120 align="center" BGCOLOR="CYAN"> ')
      document.write ('<input class="num" name="extprice' +rownum+'"
      value="" ')
      document.write ('size=10 onfocus = "this.blur( )"></td>')
      document.write ('</tr>')
      }
      //--></script>
      <tr>
      <td width="384" colspan="3" align="right"
      BGCOLOR="LIMEGR EEN">Subtotal: </td>
      <td width="120" align="center" BGCOLOR="LIMEGR EEN"><input class="num"
      name="subtotal" size="10" onfocus="this.b lur()"></td></tr>
      <tr><td width="264" colspan="2" BGCOLOR="CYAN"> <input type="checkbox"
      name="Taxable" value="true" onclick="update Totals()">Click here if you
      live in <script>documen t.write(Taxable State)</script></td>
      <td width="120" align="right" BGCOLOR="LIMEGR EEN">Sales Tax: </td>
      <td width="120" align="center" BGCOLOR="CYAN"> <input class="num"
      name="salestax" size="10" onfocus="this.b lur()"></td>
      </tr>
      <tr>
      <td width="384" colspan="3" align="right" BGCOLOR="YELLOW ">Grand
      Total:</td>
      <td width="120" align="center" BGCOLOR="#80000 0"><input class="num"
      name="grandtota l" size="10" onfocus="this.b lur()"></td></tr></table>

      </body>
      </html>


      Regards,
      Mistral

      Comment

      • Dr John Stockton

        #4
        Re: SIMPLE Javascript Calculator

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

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

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

        Read the newsgroup FAQ.

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

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

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

        Read the newsgroup FAQ.


        ===

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



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

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

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

        Comment

        • richardmgreen

          #5
          Re: SIMPLE Javascript Calculator

          Lee

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

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

          Regards

          Richard

          Lee wrote:
          richardmgreen said:

          This looks a little complexfor my needs. If I only have two drop downs
          (A & B), how would I do the following:-
          Multiply B by 2
          Add on A
          add on a constants (C) and then output the result to a small read-only
          text-box. It can be changed from read-only if necessary.
          >
          There's no real point in making the total read-only. The user can
          still change the value before sending it to you, so you absolutely
          must recalculate the total price on the server side.
          >
          >
          <html>
          <head>
          <title>Widget Sales</title>
          <script type="text/javascript">
          >
          var price = { pr_widget : 5.00,
          pr_widgelet : 7.00
          };
          var someConstant=10 ;
          >
          function updateTotal(f) {
          var total=0;
          var itemName;
          for (item in price) {
          if (itemName=item. match(/pr_(.*)/)) {
          itemName=itemNa me[1];
          if(f.elements[itemName]) {
          total+=f.elemen ts[itemName].selectedIndex* price[item];
          }
          }
          }
          if(total>0) {
          total+=someCons tant;
          }
          f.total.value=t otal;
          }
          >
          </script>
          </head>
          <body>
          <form>
          <p>Select the number of each item:</p>
          <select name="widget">
          <option>No Widgets</option>
          <option>One Widget</option>
          <option>Two Widget</option>
          <option>Three Widget</option>
          <option>Four Widget</option>
          </select>
          <select name="widgelet" >
          <option>No Widgelets</option>
          <option>One Widgelet</option>
          <option>Two Widgelet</option>
          <option>Three Widgelet</option>
          <option>Four Widgelet</option>
          </select>
          <br>
          <input type="button" value="Update Total" onclick="update Total(this.form )">
          <input name="total">
          </form>
          </body>
          </html>
          >
          >
          --

          Comment

          • Richard Cornford

            #6
            Re: SIMPLE Javascript Calculator

            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.


            Comment

            • richardmgreen

              #7
              Re: SIMPLE Javascript Calculator

              In which case, can someone please tell me why thispiece of code isn't
              working:-

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

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

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

              All help gratefully recevied.

              Richard


              Richard Cornford wrote:
              Dr John Stockton wrote:
              <snip>
              Lee's code does not work for me - button gives "Object
              doesn't support this action", line 14 char 5. I don't
              see why - the line is
              for (item in price) {
              But for (var item in price) { works.
              <snip>
              >
              Because IE browsers use the window/global object to implement the -
              frames - collection the window/global object has an - item - method.
              Without declaring - item - as a global variable the Identifier will be
              scope resolved as that - item - method of the global/window object and
              as a host provided method it is allowed to be read only, so assignments
              to - item - may (and clearly do) error.
              >
              Perversely, as it is a method, on IE browsers - typeof item - returns
              'string'.
              >
              Richard.

              Comment

              • mistral

                #8
                Re: SIMPLE Javascript Calculator

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

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

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

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

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

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

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

                here is script itself:


                function OrderForm(prefi x, firstChoice) {

                this.prefix = prefix ? prefix : '';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                }

                Comment

                • richardmgreen

                  #9
                  Re: SIMPLE Javascript Calculator

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

                  mistral wrote:
                  richardmgreen писал(а):
                  >
                  In which case, can someone please tell me why thispiece of code isn't
                  working:-
                  >
                  <script language="text/javascript">
                  var someConstant=25 ;
                  function updateTotal(pho tos,videos) {
                  var total=0;
                  var photos;
                  var videos;
                  totalprice+=(vi deos*2);
                  totalprice+=pho tos;
                  if(total>0) {
                  total+=someCons tant;
                  }
                  document.calcul ate.totalprice. value=total;
                  }
                  }
                  </script>
                  >
                  and here's the line that calls the procedure (theoretically) :-
                  <input value="Get Price"
                  onclick="update total(numberofp hotos,numberofv ideos)" type="button">
                  >
                  I'm trying to do some paramter passing which is probably where I'm
                  falling over.
                  >
                  All help gratefully recevied.
                  >
                  Richard
                  >
                  -------------------------------------------------------------------------
                  >
                  Look at this script instead, simple and convenient - total an Order
                  Form (a script that totals items using checkboxes and/or select lists).
                  >
                  How to do:
                  1.Download the script: http://ez-files.net/download.php?file=c4e6799b
                  >
                  2. Include the script. Put the following between the <head></headtags
                  in your page.
                  <script type="text/javascript" src="orderform0 3.js"></script>
                  >
                  3. Set up to instantiate an OrderForm object when the page loads.
                  <script type="text/javascript">
                  //<![CDATA[
                  window.onload = setupScripts;
                  function setupScripts()
                  {
                  var anOrder1 = new OrderForm();
                  }
                  //]]>
                  </script>
                  >
                  4. Make sure your html matches the naming conventions in the OrderForm
                  script, or change the values in the script. You need unique ids for the
                  form, text output, checkboxes, select lists, and the span tags that
                  wrap the prices. Here is a simple xhtml example with the default name
                  formats.
                  <form id="frmOrder">
                  <p>
                  <input type="checkbox" id="chk0" />
                  Wonder Widget
                  $<span id="txtPrice0"> 10</span>
                  <select id="sel0">
                  <option value="val0">0</option>
                  <option value="val1">1</option>
                  <option value="val2">2</option>
                  <option value="val3">3</option>
                  </select>
                  </p>
                  <p>
                  <input type="checkbox" id="chk1" />
                  Snow Widget
                  $<span id="txtPrice1"> 20</span>
                  <select id="sel1">
                  <option value="val0">0</option>
                  <option value="val1">1</option>
                  <option value="val2">2</option>
                  </select>
                  </p>
                  <p>
                  <input type="text" id="txtTotal" size="8" />
                  </p>
                  </form>
                  >
                  5. That's all you should need to get it working. Most changes to the
                  html (such as removing the checkboxes) shouldn't require changes to the
                  script. Refer to the Notes below for additional tips.
                  >
                  here is script itself:
                  >
                  >
                  function OrderForm(prefi x, firstChoice) {
                  >
                  this.prefix = prefix ? prefix : '';
                  >
                  // *************** *************
                  // Configure here
                  // *************** *************
                  // names - Set these according to how the html ids are set
                  this.FORM_NAME = this.prefix + 'frmOrder';
                  this.BTN_TOTAL = this.prefix + 'btnTotal';
                  this.TXT_OUT = this.prefix + 'txtTotal';
                  >
                  // partial names - Set these according to how the html ids are set
                  this.CHK = this.prefix + 'chk';
                  this.SEL = this.prefix + 'sel';
                  this.PRICE = this.prefix + 'txtPrice';
                  >
                  // if the drop down has the first choice after index 1
                  // this is used when checking or unchecking a checkbox
                  this.firstChoic e = firstChoice ? firstChoice : 1;
                  // *************** *************
                  >
                  // form
                  this.frm = document.getEle mentById(this.F ORM_NAME);
                  >
                  // checkboxes
                  this.chkReg = new RegExp(this.CHK + '([0-9]+)');
                  this.getCheck = function(chkId) {
                  return document.getEle mentById(this.C HK + chkId);
                  };
                  >
                  // selects
                  this.selReg = new RegExp(this.SEL + '([0-9]+)');
                  this.getSelect = function(selId) {
                  return document.getEle mentById(this.S EL + selId);
                  };
                  >
                  // price spans
                  this.priceReg = new RegExp(this.PRI CE + '([0-9]+)');
                  >
                  // text output
                  this.txtOut = document.getEle mentById(this.T XT_OUT);
                  >
                  // button
                  this.btnTotal = document.getEle mentById(this.B TN_TOTAL);
                  >
                  // price array
                  this.prices = new Array();
                  >
                  var o = this;
                  this.getCheckEv ent = function() {
                  return function() {
                  o.checkRetotal( o, this);
                  };
                  };
                  >
                  this.getSelectE vent = function() {
                  return function() {
                  o.totalCost(o);
                  };
                  };
                  >
                  this.getBtnEven t = function() {
                  return function() {
                  o.totalCost(o);
                  };
                  };
                  >
                  /*
                  * Calculate the cost
                  *
                  * Required:
                  * Span tags around the prices with IDs formatted
                  * so each item's numbers correspond its select elements and input
                  checkboxes.
                  */
                  this.totalCost = function(orderO bj) {
                  var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
                  var total = 0.0;
                  for (var i=0; i<spanObj.lengt h; i++) {
                  var regResult = orderObj.priceR eg.exec(spanObj[i].id);
                  if (regResult) {
                  var itemNum = regResult[1];
                  var chkObj = orderObj.getChe ck(itemNum);
                  var selObj = orderObj.getSel ect(itemNum);
                  var price = orderObj.prices[itemNum];
                  var quantity = 0;
                  if (selObj) {
                  quantity = parseFloat(selO bj.options[selObj.selected Index].text);
                  quantity = isNaN(quantity) ? 0 : quantity;
                  if (chkObj) chkObj.checked = quantity;
                  } else if (chkObj) {
                  quantity = chkObj.checked ? 1 : 0;
                  }
                  total += quantity * price;
                  }
                  }
                  orderObj.txtOut .value = total;
                  };
                  >
                  /*
                  * Handle clicks on the checkboxes
                  *
                  * Required:
                  * The corresponding select elements and input checkboxes need to be
                  numbered the same
                  *
                  */
                  this.checkRetot al = function(orderO bj, obj) {
                  var regResult = orderObj.chkReg .exec(obj.id);
                  if (regResult) {
                  var optObj = orderObj.getSel ect(regResult[1]);
                  if (optObj) {
                  if (obj.checked) {
                  optObj.selected Index = orderObj.firstC hoice;
                  } else {
                  optObj.selected Index = 0;
                  }
                  }
                  orderObj.totalC ost(orderObj);
                  }
                  };
                  >
                  /*
                  * Set up events
                  */
                  this.setEvents = function(orderO bj) {
                  var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
                  for (var i=0; i<spanObj.lengt h; i++) {
                  var regResult = orderObj.priceR eg.exec(spanObj[i].id);
                  if (regResult) {
                  var itemNum = regResult[1];
                  var chkObj = orderObj.getChe ck(itemNum);
                  var selObj = orderObj.getSel ect(itemNum);
                  if (chkObj) {
                  chkObj.onclick = orderObj.getChe ckEvent();
                  }
                  if (selObj) {
                  selObj.onchange = orderObj.getSel ectEvent();
                  }
                  if (orderObj.btnTo tal) {
                  orderObj.btnTot al.onclick = orderObj.getBtn Event();
                  }
                  }
                  }
                  };
                  this.setEvents( this);
                  >
                  /*
                  *
                  * Grab the prices from the html
                  * Required:
                  * Prices should be wrapped in span tags, numbers only.
                  */
                  this.grabPrices = function(orderO bj) {
                  var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
                  for (var i=0; i<spanObj.lengt h; i++) {
                  if (orderObj.price Reg.test(spanOb j[i].id)) {
                  var regResult = orderObj.priceR eg.exec(spanObj[i].id);
                  if (regResult) {
                  orderObj.prices[regResult[1]] = parseFloat(span Obj[i].innerHTML);
                  }
                  }
                  }
                  };
                  this.grabPrices (this);

                  }

                  Comment

                  • Richard Cornford

                    #10
                    Re: SIMPLE Javascript Calculator

                    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.

                    Comment

                    • mistral

                      #11
                      Re: SIMPLE Javascript Calculator


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

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

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

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

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

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

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

                      here is script itself:


                      function OrderForm(prefi x, firstChoice) {

                      this.prefix = prefix ? prefix : '';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                      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>Descrip tion<TH>Price<T H 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><I NPUT TYPE="radio"
                      NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
                      distotal(-800);}"No
                      <TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј1 2.00
                      <TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2 ==
                      'off') { r2='on'; distotal(1200); }">Yes<TD><INPU T TYPE="radio"
                      NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
                      distotal(-1200);}"No
                      <TR><TD>The Computer game<TD ALIGN=RIGHT>Ј3 5.00
                      <TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3 ==
                      'off') { r3='on'; distotal(3500); } ">Yes<TD><I NPUT TYPE="radio"
                      NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
                      distotal(-3500);} "No<BR>
                      <TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј1 00.00
                      <TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4 ==
                      'off') { r4='on'; distotal(10000) ;} ">Yes<TD><I NPUT 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.b lur()" ></TD>

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

                      </FORM>

                      </CENTER>


                      Rgrds
                      Mistral

                      Comment

                      • richardmgreen

                        #12
                        Re: SIMPLE Javascript Calculator

                        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(pho tos,videos) {
                        var total=0;
                        var photos;
                        var videos;
                        totalprice+=(vi deos*2);
                        totalprice+=pho tos;
                        if(total>0) {
                        total+=someCons tant;
                        }
                        document.calcul ate.totalprice. value=total;
                        }
                        }
                        </script>
                        >
                        and here's the line that calls the procedure (theoretically) :-
                        <input value="Get Price"
                        onclick="update total(numberofp hotos,numberofv ideos)" type="button">
                        >
                        I'm trying to do some paramter passing which is probably where I'm
                        falling over.
                        >
                        All help gratefully recevied.
                        >
                        Richard
                        >
                        -------------------------------------------------------------------------
                        >
                        Look at this script instead, simple and convenient - total an Order
                        Form (a script that totals items using checkboxes and/or select lists).
                        >
                        How to do:
                        1.Download the script: http://ez-files.net/download.php?file=c4e6799b
                        >
                        2. Include the script. Put the following between the <head></headtags
                        in your page.
                        <script type="text/javascript" src="orderform0 3.js"></script>
                        >
                        3. Set up to instantiate an OrderForm object when the page loads.
                        <script type="text/javascript">
                        //<![CDATA[
                        window.onload = setupScripts;
                        function setupScripts()
                        {
                        var anOrder1 = new OrderForm();
                        }
                        //]]>
                        </script>
                        >
                        4. Make sure your html matches the naming conventions in the OrderForm
                        script, or change the values in the script. You need unique ids for the
                        form, text output, checkboxes, select lists, and the span tags that
                        wrap the prices. Here is a simple xhtml example with the default name
                        formats.
                        <form id="frmOrder">
                        <p>
                        <input type="checkbox" id="chk0" />
                        Wonder Widget
                        $<span id="txtPrice0"> 10</span>
                        <select id="sel0">
                        <option value="val0">0</option>
                        <option value="val1">1</option>
                        <option value="val2">2</option>
                        <option value="val3">3</option>
                        </select>
                        </p>
                        <p>
                        <input type="checkbox" id="chk1" />
                        Snow Widget
                        $<span id="txtPrice1"> 20</span>
                        <select id="sel1">
                        <option value="val0">0</option>
                        <option value="val1">1</option>
                        <option value="val2">2</option>
                        </select>
                        </p>
                        <p>
                        <input type="text" id="txtTotal" size="8" />
                        </p>
                        </form>
                        >
                        5. That's all you should need to get it working. Most changes to the
                        html (such as removing the checkboxes) shouldn't require changes to the
                        script. Refer to the Notes below for additional tips.
                        >
                        here is script itself:
                        >
                        >
                        function OrderForm(prefi x, firstChoice) {
                        >
                        this.prefix = prefix ? prefix : '';
                        >
                        // *************** *************
                        // Configure here
                        // *************** *************
                        // names - Set these according to how the html ids are set
                        this.FORM_NAME = this.prefix + 'frmOrder';
                        this.BTN_TOTAL = this.prefix + 'btnTotal';
                        this.TXT_OUT = this.prefix + 'txtTotal';
                        >
                        // partial names - Set these according to how the html ids are set
                        this.CHK = this.prefix + 'chk';
                        this.SEL = this.prefix + 'sel';
                        this.PRICE = this.prefix + 'txtPrice';
                        >
                        // if the drop down has the first choice after index 1
                        // this is used when checking or unchecking a checkbox
                        this.firstChoic e = firstChoice ? firstChoice : 1;
                        // *************** *************
                        >
                        // form
                        this.frm = document.getEle mentById(this.F ORM_NAME);
                        >
                        // checkboxes
                        this.chkReg = new RegExp(this.CHK + '([0-9]+)');
                        this.getCheck = function(chkId) {
                        return document.getEle mentById(this.C HK + chkId);
                        };
                        >
                        // selects
                        this.selReg = new RegExp(this.SEL + '([0-9]+)');
                        this.getSelect = function(selId) {
                        return document.getEle mentById(this.S EL + selId);
                        };
                        >
                        // price spans
                        this.priceReg = new RegExp(this.PRI CE + '([0-9]+)');
                        >
                        // text output
                        this.txtOut = document.getEle mentById(this.T XT_OUT);
                        >
                        // button
                        this.btnTotal = document.getEle mentById(this.B TN_TOTAL);
                        >
                        // price array
                        this.prices = new Array();
                        >
                        var o = this;
                        this.getCheckEv ent = function() {
                        return function() {
                        o.checkRetotal( o, this);
                        };
                        };
                        >
                        this.getSelectE vent = function() {
                        return function() {
                        o.totalCost(o);
                        };
                        };
                        >
                        this.getBtnEven t = function() {
                        return function() {
                        o.totalCost(o);
                        };
                        };
                        >
                        /*
                        * Calculate the cost
                        *
                        * Required:
                        * Span tags around the prices with IDs formatted
                        * so each item's numbers correspond its select elements and input
                        checkboxes.
                        */
                        this.totalCost = function(orderO bj) {
                        var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
                        var total = 0.0;
                        for (var i=0; i<spanObj.lengt h; i++) {
                        var regResult = orderObj.priceR eg.exec(spanObj[i].id);
                        if (regResult) {
                        var itemNum = regResult[1];
                        var chkObj = orderObj.getChe ck(itemNum);
                        var selObj = orderObj.getSel ect(itemNum);
                        var price = orderObj.prices[itemNum];
                        var quantity = 0;
                        if (selObj) {
                        quantity = parseFloat(selO bj.options[selObj.selected Index].text);
                        quantity = isNaN(quantity) ? 0 : quantity;
                        if (chkObj) chkObj.checked = quantity;
                        } else if (chkObj) {
                        quantity = chkObj.checked ? 1 : 0;
                        }
                        total += quantity * price;
                        }
                        }
                        orderObj.txtOut .value = total;
                        };
                        >
                        /*
                        * Handle clicks on the checkboxes
                        *
                        * Required:
                        * The corresponding select elements and input checkboxes need to be
                        numbered the same
                        *
                        */
                        this.checkRetot al = function(orderO bj, obj) {
                        var regResult = orderObj.chkReg .exec(obj.id);
                        if (regResult) {
                        var optObj = orderObj.getSel ect(regResult[1]);
                        if (optObj) {
                        if (obj.checked) {
                        optObj.selected Index = orderObj.firstC hoice;
                        } else {
                        optObj.selected Index = 0;
                        }
                        }
                        orderObj.totalC ost(orderObj);
                        }
                        };
                        >
                        /*
                        * Set up events
                        */
                        this.setEvents = function(orderO bj) {
                        var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
                        for (var i=0; i<spanObj.lengt h; i++) {
                        var regResult = orderObj.priceR eg.exec(spanObj[i].id);
                        if (regResult) {
                        var itemNum = regResult[1];
                        var chkObj = orderObj.getChe ck(itemNum);
                        var selObj = orderObj.getSel ect(itemNum);
                        if (chkObj) {
                        chkObj.onclick = orderObj.getChe ckEvent();
                        }
                        if (selObj) {
                        selObj.onchange = orderObj.getSel ectEvent();
                        }
                        if (orderObj.btnTo tal) {
                        orderObj.btnTot al.onclick = orderObj.getBtn Event();
                        }
                        }
                        }
                        };
                        this.setEvents( this);
                        >
                        /*
                        *
                        * Grab the prices from the html
                        * Required:
                        * Prices should be wrapped in span tags, numbers only.
                        */
                        this.grabPrices = function(orderO bj) {
                        var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
                        for (var i=0; i<spanObj.lengt h; i++) {
                        if (orderObj.price Reg.test(spanOb j[i].id)) {
                        var regResult = orderObj.priceR eg.exec(spanObj[i].id);
                        if (regResult) {
                        orderObj.prices[regResult[1]] = parseFloat(span Obj[i].innerHTML);
                        }
                        }
                        }
                        };
                        this.grabPrices (this);
                        >
                        }
                        >
                        ----------------------------------------------------
                        >
                        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>Descrip tion<TH>Price<T H 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><I NPUT TYPE="radio"
                        NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
                        distotal(-800);}"No
                        <TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј1 2.00
                        <TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2 ==
                        'off') { r2='on'; distotal(1200); }">Yes<TD><INPU T TYPE="radio"
                        NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
                        distotal(-1200);}"No
                        <TR><TD>The Computer game<TD ALIGN=RIGHT>Ј3 5.00
                        <TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3 ==
                        'off') { r3='on'; distotal(3500); } ">Yes<TD><I NPUT TYPE="radio"
                        NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
                        distotal(-3500);} "No<BR>
                        <TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј1 00.00
                        <TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4 ==
                        'off') { r4='on'; distotal(10000) ;} ">Yes<TD><I NPUT 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.b lur()" ></TD>
                        >
                        <TR><TD ALIGN=RIGHT>+ VAT (17.5% Tax):<TD ALIGN=RIGHT>
                        <INPUT ALIGN=RIGHT type="text" NAME="vat" VALUE="" SIZE=7
                        onFocus="this.b lur()" ></TD>
                        <TR><TD ALIGN=RIGHT COLSPAN=2>
                        <FONT SIZE=+2><B>Tota l: Ј </B></FONT>
                        <INPUT ALIGN=RIGHT type="text" NAME="tot" VALUE="" SIZE=7
                        onFocus="this.b lur()" ></TD></TABLE>
                        </UL>

                        </FORM>

                        </CENTER>


                        Rgrds
                        Mistral

                        Comment

                        • mistral

                          #13
                          Re: SIMPLE Javascript Calculator


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

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

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

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

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

                          4. Make sure your html matches the naming conventions in the OrderForm
                          script, or change the values in the script. You need unique ids 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(prefi x, firstChoice) {

                          this.prefix = prefix ? prefix : '';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                          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>Descrip tion<TH>Price<T H 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><I NPUT TYPE="radio"
                          NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
                          distotal(-800);}"No
                          <TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј1 2.00
                          <TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2==
                          'off') { r2='on'; distotal(1200); }">Yes<TD><INPU T TYPE="radio"
                          NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
                          distotal(-1200);}"No
                          <TR><TD>The Computer game<TD ALIGN=RIGHT>Ј3 5.00
                          <TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3==
                          'off') { r3='on'; distotal(3500); } ">Yes<TD><I NPUT TYPE="radio"
                          NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
                          distotal(-3500);} "No<BR>
                          <TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј1 00.00
                          <TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4==
                          'off') { r4='on'; distotal(10000) ;} ">Yes<TD><I NPUT 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.b lur()" ></TD>

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

                          </FORM>

                          </CENTER>


                          Rgrds
                          Mistral
                          --------------------

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

                          <code>
                          <HTML>
                          <HEAD>

                          <SCRIPT LANGUAGE="JavaS cript">

                          <!-- 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.su b.value="Ј"+Ad dDecimal(sub);
                          document.msg.va t.value="Ј"+Ad dDecimal(vat);
                          document.msg.to t.value=AddDeci mal(total+vat);

                          }

                          function AddDecimal(numb er) {
                          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(n um.length - 2, num.length);
                          }
                          return withdecimal;
                          }

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

                          </SCRIPT>

                          <TITLE>JavaScri pt Order Form</TITLE>
                          </HEAD>


                          <BODY BGCOLOR="#fffff f" 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>Descrip tion<TH>Price<T H 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><I NPUT TYPE="radio"
                          NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
                          distotal(-800);}"No
                          <TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј1 2.00
                          <TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2 ==
                          'off') { r2='on'; distotal(1200); }">Yes<TD><INPU T TYPE="radio"
                          NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
                          distotal(-1200);}"No
                          <TR><TD>The Computer game<TD ALIGN=RIGHT>Ј3 5.00
                          <TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3 ==
                          'off') { r3='on'; distotal(3500); } ">Yes<TD><I NPUT TYPE="radio"
                          NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
                          distotal(-3500);} "No<BR>
                          <TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј1 00.00
                          <TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4 ==
                          'off') { r4='on'; distotal(10000) ;} ">Yes<TD><I NPUT 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.b lur()" ></TD>

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

                          </FORM>

                          </CENTER>

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

                          Mistral

                          Comment

                          • richardmgreen

                            #14
                            Re: SIMPLE Javascript Calculator

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

                            Richard
                            >
                            -------------------------------------------------------------------------
                            >
                            Look at this script instead, simple and convenient - total an Order
                            Form (a script that totals items using checkboxes and/or select lists).
                            >
                            How to do:
                            1.Download the script: http://ez-files.net/download.php?file=c4e6799b
                            >
                            2. Include the script. Put the following between the <head></headtags
                            in your page.
                            <script type="text/javascript" src="orderform0 3.js"></script>
                            >
                            3. Set up to instantiate an OrderForm object when the page loads.
                            <script type="text/javascript">
                            //<![CDATA[
                            window.onload = setupScripts;
                            function setupScripts()
                            {
                            var anOrder1 = new OrderForm();
                            }
                            //]]>
                            </script>
                            >
                            4. Make sure your html matches the naming conventions in the OrderForm
                            script, or change the values in the script. You need unique ids for the
                            form, text output, checkboxes, select lists, and the span tags that
                            wrap the prices. Here is a simple xhtml example with the default name
                            formats.
                            <form id="frmOrder">
                            <p>
                            <input type="checkbox" id="chk0" />
                            Wonder Widget
                            $<span id="txtPrice0"> 10</span>
                            <select id="sel0">
                            <option value="val0">0</option>
                            <option value="val1">1</option>
                            <option value="val2">2</option>
                            <option value="val3">3</option>
                            </select>
                            </p>
                            <p>
                            <input type="checkbox" id="chk1" />
                            Snow Widget
                            $<span id="txtPrice1"> 20</span>
                            <select id="sel1">
                            <option value="val0">0</option>
                            <option value="val1">1</option>
                            <option value="val2">2</option>
                            </select>
                            </p>
                            <p>
                            <input type="text" id="txtTotal" size="8" />
                            </p>
                            </form>
                            >
                            5. That's all you should need to get it working. Most changes to the
                            html (such as removing the checkboxes) shouldn't require changes to the
                            script. Refer to the Notes below for additional tips.
                            >
                            here is script itself:
                            >
                            >
                            function OrderForm(prefi x, firstChoice) {
                            >
                            this.prefix = prefix ? prefix : '';
                            >
                            // *************** *************
                            // Configure here
                            // *************** *************
                            // names - Set these according to how the html ids are set
                            this.FORM_NAME = this.prefix + 'frmOrder';
                            this.BTN_TOTAL = this.prefix + 'btnTotal';
                            this.TXT_OUT = this.prefix + 'txtTotal';
                            >
                            // partial names - Set these according to how the html ids are set
                            this.CHK = this.prefix + 'chk';
                            this.SEL = this.prefix + 'sel';
                            this.PRICE = this.prefix + 'txtPrice';
                            >
                            // if the drop down has the first choice after index 1
                            // this is used when checking or unchecking a checkbox
                            this.firstChoic e = firstChoice ? firstChoice : 1;
                            // *************** *************
                            >
                            // form
                            this.frm = document.getEle mentById(this.F ORM_NAME);
                            >
                            // checkboxes
                            this.chkReg = new RegExp(this.CHK + '([0-9]+)');
                            this.getCheck = function(chkId) {
                            return document.getEle mentById(this.C HK + chkId);
                            };
                            >
                            // selects
                            this.selReg = new RegExp(this.SEL + '([0-9]+)');
                            this.getSelect = function(selId) {
                            return document.getEle mentById(this.S EL + selId);
                            };
                            >
                            // price spans
                            this.priceReg = new RegExp(this.PRI CE + '([0-9]+)');
                            >
                            // text output
                            this.txtOut = document.getEle mentById(this.T XT_OUT);
                            >
                            // button
                            this.btnTotal = document.getEle mentById(this.B TN_TOTAL);
                            >
                            // price array
                            this.prices = new Array();
                            >
                            var o = this;
                            this.getCheckEv ent = function() {
                            return function() {
                            o.checkRetotal( o, this);
                            };
                            };
                            >
                            this.getSelectE vent = function() {
                            return function() {
                            o.totalCost(o);
                            };
                            };
                            >
                            this.getBtnEven t = function() {
                            return function() {
                            o.totalCost(o);
                            };
                            };
                            >
                            /*
                            * Calculate the cost
                            *
                            * Required:
                            * Span tags around the prices with IDs formatted
                            * so each item's numbers correspond its select elements and input
                            checkboxes.
                            */
                            this.totalCost = function(orderO bj) {
                            var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
                            var total = 0.0;
                            for (var i=0; i<spanObj.lengt h; i++) {
                            var regResult = orderObj.priceR eg.exec(spanObj[i].id);
                            if (regResult) {
                            var itemNum = regResult[1];
                            var chkObj = orderObj.getChe ck(itemNum);
                            var selObj = orderObj.getSel ect(itemNum);
                            var price = orderObj.prices[itemNum];
                            var quantity = 0;
                            if (selObj) {
                            quantity = parseFloat(selO bj.options[selObj.selected Index]..text);
                            quantity = isNaN(quantity) ? 0 : quantity;
                            if (chkObj) chkObj.checked = quantity;
                            } else if (chkObj) {
                            quantity = chkObj.checked ? 1 : 0;
                            }
                            total += quantity * price;
                            }
                            }
                            orderObj.txtOut .value = total;
                            };
                            >
                            /*
                            * Handle clicks on the checkboxes
                            *
                            * Required:
                            * The corresponding select elements and input checkboxes need to be
                            numbered the same
                            *
                            */
                            this.checkRetot al = function(orderO bj, obj) {
                            var regResult = orderObj.chkReg .exec(obj.id);
                            if (regResult) {
                            var optObj = orderObj.getSel ect(regResult[1]);
                            if (optObj) {
                            if (obj.checked) {
                            optObj.selected Index = orderObj.firstC hoice;
                            } else {
                            optObj.selected Index = 0;
                            }
                            }
                            orderObj.totalC ost(orderObj);
                            }
                            };
                            >
                            /*
                            * Set up events
                            */
                            this.setEvents = function(orderO bj) {
                            var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
                            for (var i=0; i<spanObj.lengt h; i++) {
                            var regResult = orderObj.priceR eg.exec(spanObj[i].id);
                            if (regResult) {
                            var itemNum = regResult[1];
                            var chkObj = orderObj.getChe ck(itemNum);
                            var selObj = orderObj.getSel ect(itemNum);
                            if (chkObj) {
                            chkObj.onclick = orderObj.getChe ckEvent();
                            }
                            if (selObj) {
                            selObj.onchange = orderObj.getSel ectEvent();
                            }
                            if (orderObj.btnTo tal) {
                            orderObj.btnTot al.onclick = orderObj.getBtn Event();
                            }
                            }
                            }
                            };
                            this.setEvents( this);
                            >
                            /*
                            *
                            * Grab the prices from the html
                            * Required:
                            * Prices should be wrapped in span tags, numbers only.
                            */
                            this.grabPrices = function(orderO bj) {
                            var spanObj = orderObj.frm.ge tElementsByTagN ame('span');
                            for (var i=0; i<spanObj.lengt h; i++) {
                            if (orderObj.price Reg.test(spanOb j[i].id)) {
                            var regResult = orderObj.priceR eg.exec(spanObj[i].id);
                            if (regResult) {
                            orderObj.prices[regResult[1]] = parseFloat(span Obj[i].innerHTML);
                            }
                            }
                            }
                            };
                            this.grabPrices (this);
                            >
                            }
                            >
                            ----------------------------------------------------
                            >
                            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>Descrip tion<TH>Price<T H 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><I NPUT TYPE="radio"
                            NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
                            distotal(-800);}"No
                            <TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј1 2.00
                            <TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2 ==
                            'off') { r2='on'; distotal(1200); }">Yes<TD><INPU T TYPE="radio"
                            NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
                            distotal(-1200);}"No
                            <TR><TD>The Computer game<TD ALIGN=RIGHT>Ј3 5.00
                            <TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3 ==
                            'off') { r3='on'; distotal(3500); } ">Yes<TD><I NPUT TYPE="radio"
                            NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
                            distotal(-3500);} "No<BR>
                            <TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј1 00.00
                            <TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4 ==
                            'off') { r4='on'; distotal(10000) ;} ">Yes<TD><I NPUT 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.b lur()" ></TD>
                            >
                            <TR><TD ALIGN=RIGHT>+ VAT (17.5% Tax):<TD ALIGN=RIGHT>
                            <INPUT ALIGN=RIGHT type="text" NAME="vat" VALUE="" SIZE=7
                            onFocus="this.b lur()" ></TD>
                            <TR><TD ALIGN=RIGHT COLSPAN=2>
                            <FONT SIZE=+2><B>Tota l: Ј </B></FONT>
                            <INPUT ALIGN=RIGHT type="text" NAME="tot" VALUE="" SIZE=7
                            onFocus="this.b lur()" ></TD></TABLE>
                            </UL>
                            >
                            </FORM>
                            >
                            </CENTER>
                            >
                            >
                            Rgrds
                            Mistral
                            >
                            --------------------
                            >
                            sorry, one script part was missed, here you go:
                            >
                            <code>
                            <HTML>
                            <HEAD>
                            >
                            <SCRIPT LANGUAGE="JavaS cript">
                            >
                            <!-- 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.su b.value="Ј"+Ad dDecimal(sub);
                            document.msg.va t.value="Ј"+Ad dDecimal(vat);
                            document.msg.to t.value=AddDeci mal(total+vat);
                            >
                            }
                            >
                            function AddDecimal(numb er) {
                            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(n um.length - 2, num.length);
                            }
                            return withdecimal;
                            }
                            >
                            // -- End of JavaScript code -------------- -->
                            >
                            </SCRIPT>
                            >
                            <TITLE>JavaScri pt Order Form</TITLE>
                            </HEAD>
                            >
                            >
                            <BODY BGCOLOR="#fffff f" 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>Descrip tion<TH>Price<T H 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><I NPUT TYPE="radio"
                            NAME="rad1" CHECKED onclick="if (r1 == 'on') {r1='off';
                            distotal(-800);}"No
                            <TR><TD>The Fishy T-Shirt<TD ALIGN=RIGHT>Ј1 2.00
                            <TD><INPUT TYPE="radio" NAME="rad2" VALUE="yes" onclick="if (r2 ==
                            'off') { r2='on'; distotal(1200); }">Yes<TD><INPU T TYPE="radio"
                            NAME="rad2" CHECKED onclick="if (r2 == 'on') {r2='off';
                            distotal(-1200);}"No
                            <TR><TD>The Computer game<TD ALIGN=RIGHT>Ј3 5.00
                            <TD><INPUT TYPE="radio" NAME="rad3" VALUE="yes" onclick="if (r3 ==
                            'off') { r3='on'; distotal(3500); } ">Yes<TD><I NPUT TYPE="radio"
                            NAME="rad3" CHECKED onclick="if (r3 == 'on') {r3='off';
                            distotal(-3500);} "No<BR>
                            <TR><TD>The Cuddly Toy<TD ALIGN=RIGHT>Ј1 00.00
                            <TD><INPUT TYPE="radio" NAME="rad4" VALUE="yes" onclick="if (r4 ==
                            'off') { r4='on'; distotal(10000) ;} ">Yes<TD><I NPUT 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.b lur()" ></TD>
                            >
                            <TR><TD ALIGN=RIGHT>+ VAT (17.5% Tax):<TD ALIGN=RIGHT>
                            <INPUT ALIGN=RIGHT type="text" NAME="vat" VALUE="" SIZE=7
                            onFocus="this.b lur()" ></TD>
                            <TR><TD ALIGN=RIGHT COLSPAN=2>
                            <FONT SIZE=+2><B>Tota l: Ј </B></FONT>
                            <INPUT ALIGN=RIGHT type="text" NAME="tot" VALUE="" SIZE=7
                            onFocus="this.b lur()" ></TD></TABLE>
                            </UL>
                            >
                            </FORM>

                            </CENTER>

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

                            Mistral

                            Comment

                            • Jim Carlock

                              #15
                              Re: SIMPLE Javascript Calculator

                              <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.va lue or by getting the
                              index, form.selItem.se lectedIndex.

                              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.dt d">
                              <html>
                              <head>
                              <title>Giggle s 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;li ne-height:1.5em; }
                              ..d1 { float:left;widt h:120px;margin: 0.2em;text-align:right;cle ar:none; }
                              ..d2 { float:left;widt h:300px;margin: 0.2em;text-align:left;clea r:none; }
                              ..d3 { width:360px;tex t-align:right;cle ar:both; }
                              ..dcb { clear:both; }
                              ..dbutt { float:none;widt h:200px;margin: 0px auto;padding:0p x;line-height:1.5em; }
                              /*
                              * Internet Explorer fails to recognize class names that
                              * begin with an underscore.
                              * For Example, "_outer_spa ce", as in:
                              * ._outer_space { ... }
                              */
                              ..o_s { margin:20px;pad ding:0px; }
                              /* without the DOCTYPE the margin:auto; fails in Internet Explorer. */
                              ..i_s { float:none;widt h:436px;margin: auto;padding:0p x;clear:both;ve rtical-align:middle; }
                              </style>
                              </head>
                              <body><div class="o_s"><di v class="i_s">
                              <h1>Giggles And Wiggles</h1>
                              <form name="PriceCalc ulator" action="">

                              <div class="dcb"><di v class="d1">Gigg les Wanted:</div><div class="d2"><inp ut type="text" name="txtGiggle Q" size="4" value="0"
                              tabindex="1" maxlength="5" onchange="Calcu late(this.form) " /<input type="text" name="txtGiggle UnitPrice" disabled="disab led"
                              value="0.00" title="Giggle Unit Price" size="6" /<input type="text" name="txtGiggle Qty" size="4" value="0" disabled="disab led" />
                              <input type="text" name="txtGiggle Total" size="5" value="0.00" maxlength="7" disabled="disab led" /></div></div>

                              <div class="dcb"><di v class="d1">Wigg les Wanted:</div><div class="d2"><inp ut type="text" name="txtWiggle Q" size="4" value="0"
                              tabindex="2" maxlength="5" onchange="Calcu late(this.form) " /<input type="text" name="txtWiggle UnitPrice" disabled="disab led"
                              value="0.00" title="Wiggle Unit Price" size="6" /<input type="text" name="txtWiggle Qty" size="4" value="0" disabled="disab led" />
                              <input type="text" name="txtWiggle Total" size="5" value="0.00" maxlength="7" disabled="disab led" /></div></div>

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

                              <div class="dbutt">< input type="button" style="text-align:center;ma rgin:0.2em;padd ing:0.20%;width :100px;border:3 px #0066bb outset;"
                              disabled="disab led" value="Calculat e" 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.txtGiggleQ ty.value = "";
                              form.txtWiggleQ ty.value = "";
                              form.txtGiggleP rice.value = "";
                              form.txtWiggleP rice.value = "";
                              }

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

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

                              function Calculate(form) {
                              iGiggleQty = QuantityGiggles (form);
                              iWiggleQty = QuantityWiggles (form);
                              form.txtGiggleQ ty.value = iGiggleQty;
                              form.txtWiggleQ ty.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.txtGiggleU nitPrice.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.txtWiggleU nitPrice.value = rWigglePrice;
                              rWiggleTotal = iWiggleQty * rWigglePrice;

                              form.txtGiggleT otal.value = rGiggleTotal;
                              form.txtWiggleT otal.value = rWiggleTotal;
                              form.txtTotal.v alue = rGiggleTotal + rWiggleTotal;
                              }
                              // -->



                              Comment

                              Working...