[Javascript] Updating a text box - calculations

Paul Novitski paul at novitskisoftware.com
Wed Feb 2 00:26:15 CST 2005


At 05:03 PM 2/1/2005, Tim Burgan wrote:
>In a form, I have 5 text boxes vertically on top of each other. Each where 
>the user can enter a dollar amount.
>
>Then in a 6th text box.. it displays 2% of the sum of the 5 text boxes.
>
>Then a 7th text box adds the values of all 6 text boxes to give a grand total.
>
>
>How in the world do I do this with Javascript?


Tim,

You can certainly do what you want in javascript; off the top of my head, 
here are some of the basic tools you'll need:

1) You can get the current value of a text box with the .value property, e.g.:

         <input id="amount1" type="text" />
...
         // get the string value of input field 1
         var sAmount1 = document.getElementById("amount1").value;

2) The numerical value of a string can be extracted using the function 
parseFloat(str), e.g.:

         // add the current amount to the running total
         nTotal += parseFloat(sAmount);

3) You can trigger a javascript function when the content of a textbox is 
changed with the onchange event:

         // run initialization function when the page loads
         window.onload = InitBoxes;

         // initialize boxes
         function InitBoxes()
         {
                 // assign the function to the onchange trigger
                 document.getElementById("amount1").onchange = AddBoxes;
                 ...
         }

         // function to be run whenever the textbox value is changed
         function AddBoxes(evt)
         {
                 // cancel event bubbling
                 if (evt)
                 {
                         event = evt;
                 }
                 event.cancelBubble = true;

                 // add values of all textboxes
                 nTotal += ...

                 // supply 2% box
                 var nTwoPercent = nTotal * 0.02;
                 document.getElementById("twopercent").value = nTwoPercent;

                 // grand total box
                 document.getElementById("total").value = nTotal + nTwoPercent;
         }

Let me know if you want help filling in the gaps in this sketch.

Paul 





More information about the Javascript mailing list