Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Need help with JS average calculator

    I need some help getting this to work. I cant get the average function to work. I have tried F12 console no errors. Where am I going wrong?

    Code:
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Average Calculator</title>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <h1 style="text-align:center;">My Average Calculator</h1>
    <script type="text/javascript">
    function getTotal() {
        var form = document.getElementById('number');
        var numb1 = parseInt(form.numb1.value);
        var numb2 = parseInt(form.numb2.value);
        var numb3 = parseInt(form.numb3.value);
        var numb4 = parseInt(form.numb4.value);
        var numb5 = parseInt(form.numb5.value);
        var total = document.getElementById('total');
        var average = document.getElementById('average');
        if (!numb1) {
            numb1 = 0;
        }
    
        if (!numb2) {
            numb2 = 0;
        }
    
        if (!numb3) {
            numb3 = 0;
        }
    
        if (!numb4) {
            numb4 = 0;
        }
        if (!numb5) {
            numb5 = 0;
        }
    
        total.innerHTML = 'Total: ' + (numb1 + numb2 + numb3 + numb4 + 
    
    numb5);
        average = (numb1 + numb2 + numb3 + numb4 + numb5) / 5;
        average.innerHTML = 'Average: ' + (total / 5);
    }
    </script>
    </head>
    <form id="number">
        
        <body>
    First Number: <input type="text" name="numb1" onkeyup="getTotal ();" />
    Second Number: <input type="text" name="numb2" onkeyup="getTotal();" />
    Third Number:  <input type="text" name="numb3" onkeyup="getTotal();" />
    Fourth Number: <input type="text" name="numb4" onkeyup="getTotal();" />
    Fifth Number:  <input type="text" name="numb5" onkeyup="getTotal();" />
            <div id="total">Total:     </div>
            <div id="average">Average: </div>
    </body>
    </html>
    I also am having issues getting everything centered.

    this is what i get
    text (box) text (box) text (box)

    what i want is
    text(box)
    text(box)
    text(box)

    centered horizonally on the web page

    *(box)= textbox

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,447
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    What *POSSIBLE* reason is there to use onkeyup???

    The average is *MEANINGLESS* until all 5 numbers have been entered.

    You are the second person today using onkeyup for no discernible reason. Where are you learning that from?
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,447
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    LOL! This is *FUNNY*!
    Code:
        var average = document.getElementById('average');
        ...
        average = (numb1 + numb2 + numb3 + numb4 + numb5) / 5;
        average.innerHTML = 'Average: ' + (total / 5);
    The assignment in red there *WIPES OUT* the prior assignment! *KABLOOEY*!
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #4
    Regular Coder
    Join Date
    Mar 2006
    Posts
    728
    Thanks
    35
    Thanked 132 Times in 123 Posts
    Code:
    <!doctype html>
    <html lang="en">
    <head>
    <meta charset= "utf-8">
    <title>Average Calculator</title>
    <style>
    #number{display:inline-block;text-align:right;}
    input{text-align:right;width:50%;}
    #nums{text-align:left;list-style-type:none;border-top:2px black solid;}
    #count{margin-left:-1em}
    </style>
    <script>
    	function sumAverage(){
    		var sum= document.getElementById('sum'), 
    		nums=document.getElementById('nums'),
    		tot= document.getElementById('total'),
    		avg= document.getElementById('average'),		
    		L=nums.getElementsByTagName('li').length,
    		val=parseInt(sum.value,10)|| 0,		
    		total=(parseInt(tot.value,10) || 0)+val,
    		next= document.createElement('li');
    		  
    		next.appendChild(document.createTextNode(val));
    		nums.appendChild(next);		
    		tot.value=total;		
    		avg.value= Math.round((total/L)*1e12)/1e12;
    		sum.value='';
    		setTimeout(function(){sum.focus()},100);
    		document.getElementById('count').innerHTML=L+' numbers:';
    	}
    	onload=function(){
    		document.getElementById('sum').focus();
    	}
    </script>
    
    </head>
    <body>
    <h1>Enter any number of numbers:</h1>
    
    <div id= "number">
    <p>Number: <input id="sum" value="" onchange="sumAverage()"> <button > Add</button><label></p>
    <p>Total: <input  id= "total" readOnly></p>
    <p>Average: <input id= "average" readOnly></p>
    <div>
    <ul id="nums">
    <li><span id="count">Numbers: </span></li>
    </ul>
    </div>
    </div>
    </body>
    </html>
    Last edited by mrhoo; 02-14-2013 at 06:07 AM. Reason: Old Pedant's point

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,447
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    Yeah, MrHoo, but what if the user has only entered 3 values? With your code, the blank values will be treated as zeroes and the average for 3 values won't be accurate.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    mrhoo (02-14-2013)

  • #6
    New to the CF scene
    Join Date
    Feb 2013
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Edit

    I have to use:

    onchange event handler
    calcAvg()
    performCalc()
    calcResult
    averageCalc()
    parseInt()



    Which sucks because I got it the way I like and now I got to change it

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,990
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    You could simply your code and trap NaN entries with

    Code:
    var n1 = Math.floor(Number(form.numb1.value))  || 0;  // i.e. assign 0 if the entry is NaN
    DO NOT use the same name/id for an HTML elemnt and a Javascript variable.

    parseInt() is really intended for converting from one number base to another. If you do use it you need to specify the radix (10) as otherwise if the user enters (e.g.) 09 it will be interpreted as octal. The correct way to obtain an integer is to use Math.floor(). Another example of poor quality teaching, but if parseInt() is required then I realise you must comply.

    Instead of the fixed divisor /5 you need to keep count of the number of numbers entered. Without using an array, you could do that by assigning an initial value of "x" to n1, n2 etc. and then including in the calculation only those variables which are != x.

    As Old Pedant says, onkeyup is totally inappropriate. You should use a button to trigger the calculation. I don't see how onchange is relevant either.

    To centre (or center in American spelling ) your input boxes:-

    Code:
    <div id = "container" style = "text-align:center"} >
    First Number: <input type="text" name="numb1" ><br>
    Second Number: <input type="text" name = "numb2" ><br>
    Third Number:  <input type="text" name="numb3"><br>
    Fourth Number: <input type="text" name="numb4"><br>
    Fifth Number:  <input type="text" name="numb5" ><br>
    </div>
    “Sex is one of the most wholesome, beautiful and natural experiences that money can buy.” - Steve Martin
    Last edited by Philip M; 02-14-2013 at 08:32 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

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