Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-13-2013, 11:43 PM   PM User | #1
jasonmcbee
New to the CF scene

 
Join Date: Feb 2013
Posts: 6
Thanks: 2
Thanked 0 Times in 0 Posts
jasonmcbee is an unknown quantity at this point
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
jasonmcbee is offline   Reply With Quote
Old 02-14-2013, 01:21 AM   PM User | #2
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,187
Thanks: 59
Thanked 3,995 Times in 3,964 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 02-14-2013, 01:24 AM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,187
Thanks: 59
Thanked 3,995 Times in 3,964 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 02-14-2013, 01:59 AM   PM User | #4
mrhoo
Regular Coder

 
Join Date: Mar 2006
Posts: 708
Thanks: 30
Thanked 127 Times in 118 Posts
mrhoo will become famous soon enoughmrhoo will become famous soon enough
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
mrhoo is offline   Reply With Quote
Old 02-14-2013, 02:03 AM   PM User | #5
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,187
Thanks: 59
Thanked 3,995 Times in 3,964 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Users who have thanked Old Pedant for this post:
mrhoo (02-14-2013)
Old 02-14-2013, 02:26 AM   PM User | #6
jasonmcbee
New to the CF scene

 
Join Date: Feb 2013
Posts: 6
Thanks: 2
Thanked 0 Times in 0 Posts
jasonmcbee is an unknown quantity at this point
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
jasonmcbee is offline   Reply With Quote
Old 02-14-2013, 08:04 AM   PM User | #7
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,036
Thanks: 197
Thanked 2,411 Times in 2,389 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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
__________________

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.

Last edited by Philip M; 02-14-2013 at 08:32 AM..
Philip M is online now   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 05:35 PM.


Advertisement
Log in to turn off these ads.