Results 1 to 3 of 3

Thread: JavaScript to calculate averages

  1. #1
    Join Date
    Feb 2005
    Posts
    54
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default JavaScript to calculate averages

    Hi all,

    I have four textboxes that will be prefilled with values when the user opens the page and I'm trying to write a script to calculate the average of these textboxes - result to appear in another textbox. For example:

    Text Box 1: 10
    Text Box 2: 15
    Text Box 3: 25
    Text Box 4: 30

    Text Box 5: 20 (trying to have this box calculate the average of boxes 1-4)

    I searched google and only found one that touched on this, but couldn't get it to work in this environment. Does anyone have anything that they have used in the past?

    Much appreciated.

    - i

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Code:
    <html>
    <head>
    <title>Average Boxes - Demo</title>
    <style type="text/css">
    input{
    width:4em;
    display:block
    }
    </style>
    <script type="text/javascript">
    function averageBoxes(){
    var avg=(Math.abs(document.boxes.textBox1.value)+Math.abs(document.boxes.textBox2.value)+Math.abs(document.boxes.textBox3.value)+Math.abs(document.boxes.textBox4.value))/4
    if (avg!==avg)
    alert('Numbers Only Please!')
    document.boxes.textBox5.value=avg
    }
    </script>
    </head>
    <body onload="averageBoxes()">
    <form name="boxes">
    Value 1:<input name="textBox1" value=15 onkeyup="averageBoxes()" type="text">
    Value 2:<input name="textBox2" value=10 onkeyup="averageBoxes()" type="text">
    Value 3:<input name="textBox3" value=25 onkeyup="averageBoxes()" type="text">
    Value 4:<input name="textBox4" value=20 onkeyup="averageBoxes()" type="text">
    Avg Val:<input name="textBox5" readonly type="text">
    </body>
    </html>
    If, as you say, the boxes are prefilled when the page loads and you don't want the user to be able to change the values at that point, you could make all the boxes readonly and get rid of the onkeyup events.
    Last edited by jscheuer1; 06-18-2005 at 05:19 AM.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Feb 2005
    Posts
    54
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Thanks jscheuer1...

    Shortly after posting, I was able to create a Javascript that did this - though probably not as efficiently as your script.

    I appreciate your reply.

    - I

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •