Solved

Statistic Calculator using Javascript

Posted on 2016-09-25
7
107 Views
Last Modified: 2016-10-05
Hello,

I have some code that I'd like to adjust to create a statistics calculator, the javascript should calculate the sum, average, max and min value when I entered a list of numbers on a web page; I'd like to use loops.  The results should be added to a list in the web page.


var i, n
var valueCount = 0;
var valueSum = 0;
var valueAverage = 0;
var valueMax = 0;
var valueMin = 0;

$( "#calculate" ).click(processValues);

function processValues() {
  $("#results" ).html( "" );//clears any list items from last calculation
  var valueString = $( "#valueList" ).val();
  var value = $.map(valueString.split(","), Number ); //this is an array
  valueCount = value.length; //get the lenght of the array (number of values)

 function sum() {
   sumofvalueString=0;
   valueString= document.GetElementById("#valueList").value.split(",");
   for(i=0; i <valueString.length; i++) {
     sumofvalueString += parseInt(valueString (i));
   }
  document.GetElementById("valueSum").innerHTML = sumofvalueString;
 }
 
  $("#results" ).append( "<li>The values entered: " + valueString + ".</li>" );
  $("#results" ).append( "<li>There are " + valueCount + " values.</li>" );
  $("#results" ).append( "<li>The Sum is " + valueSum + ".</li>" );
  $("#results" ).append( "<li>The Max is" + valueMax + ".</li>" );
  $("#results" ).append( "<li>The Min is" + valueMin + ".</li>" );
 
 

  $("#valueList").val("");
}

here is the code for the webpage

<h4>Enter numbers separated by commas and click calculate </h4>
        <input id="valueList" type="text" ><button type="button" id="calculate">Calculate Stats</button>
        <br><br>
        <H2>Results</H2>


Thanks,
0
Comment
Question by:hernandez5999
  • 4
  • 3
7 Comments
 
LVL 22

Expert Comment

by:Kim Walker
ID: 41815362
I don't see a question in your post? Are you getting an error you need help with? This sounds more like a work request than a request for assistance.
0
 
LVL 3

Author Comment

by:hernandez5999
ID: 41815794
The code is not working, when I entered the digits and click Calculate, I get nothing. I'd like to simplify the code using loops to calculate the max, min, average, and count. How do i do this? I tried to edit the question, but couldn't.
0
 
LVL 22

Accepted Solution

by:
Kim Walker earned 500 total points
ID: 41824395
There are several potential problems with the code you've provided if this is all the HTML code. I'll start with a few statements and questions that will help me determine if a problem exists and then I'll point out a few definite errors.
  1. Where in your page have you placed the javascript code you've provided? It will not work in the document head element because it references DOM objects that haven't been created yet. But it can work if placed at the bottom of the body element.
  2. The very first line of the function "processValues" references an element with the id "results". Does that element exist elsewhere on the page. It is not part of the HTML in your post.
  3. Your "processValues" function has a nested function, "sum()" which gets defined and undefined with each execution of the function "processValues". It redefines the variable "valueString". The nested function should be defined outside the scope of "processValues".
  4. The "sum()" function references an element with id "valueSum" which also isn't included in your HTML. Does it exist elsewhere on your page?

Noted problems:
  1. That same function "sum" which is nested in another function definition is never executed.
  2. The variable "valueString" in the sum function is defined to contain an array. A couple of lines later it appears that you are attempting to reference one of the values in that array using parentheses instead of square braces.
  3. Javascript is case sensitive. GetElementById is not a javascript method. getElementById, however, is.
  4. getElementById does not require the hash mark (#) as does jQuery.

I've made some minor modification to your code to make it produce some output even if it isn't complete. There are other operations that need to be executed to complete the output.
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Test Doc</title>
        <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
        
    </head>
    
    <body>
        <h4>Enter numbers separated by commas and click calculate </h4>
        <input id="valueList" type="text" ><button type="button" id="calculate">Calculate Stats</button>
        <br><br>
        <h2>Results</h2>
        <p id="valueSum"></p>
        <ul id="results"></ul>
        <script>
            var i, n
            var valueCount = 0;
            var valueSum = 0;
            var valueAverage = 0;
            var valueMax = 0;
            var valueMin = 0;
            
            $( "#calculate" ).click(processValues);
            
            function processValues() {
                $("#results" ).html( "" );//clears any list items from last calculation
                var valueString = $( "#valueList" ).val();
                var value = $.map(valueString.split(","), Number ); //this is an array
                valueCount = value.length; //get the lenght of the array (number of values)
                
                sum();
                
                $("#results" ).append( "<li>The values entered: " + valueString + ".</li>" );
                $("#results" ).append( "<li>There are " + valueCount + " values.</li>" );
                $("#results" ).append( "<li>The Sum is " + valueSum + ".</li>" );
                $("#results" ).append( "<li>The Max is" + valueMax + ".</li>" );
                $("#results" ).append( "<li>The Min is" + valueMin + ".</li>" );
                
                $("#valueList").val("");
            }
                
            function sum() {
                sumofvalueString=0;
                valueString= document.getElementById("valueList").value.split(",");
                for(i=0; i <valueString.length; i++) {
                    sumofvalueString += parseInt(valueString[i]);
                }
                document.getElementById("valueSum").innerHTML = sumofvalueString;
            }
        </script>
    </body>
</html>

Open in new window

For future reference, please format your code using the CODE button at the top of the comment window. Just select your code and click the CODE button. This makes it much easier for us to peruse the code.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Author Comment

by:hernandez5999
ID: 41831097
hello,

I looked at it and it works, I added the average, but I am having problems getting the Max and Min, but can't seem to get it. HEre is the code that I am using.

 function max() {
			maxofvalueString=value[0];
				valueString= document.getElementById("valuelist").value.split(",");
				  for(i=0; i <valueString.length; i++) 
	   {
                if(max <valueString[i])
                   max= valueString[i];
			   }
	   } 

Open in new window


thanks,
0
 
LVL 22

Assisted Solution

by:Kim Walker
Kim Walker earned 500 total points
ID: 41831113
You need to parseFloat your valueStrings to convert them from strings to numbers. If your numbers will always be positive whole numbers, you can parseInt instead.

You are using the variable name max which is not initialized. Should you be using maxofvalueString?

Since you are initializing maxofvalueString with valueString[0], you can start your loop at index 1.

function max() {
    valueString= document.getElementById("valuelist").value.split(",");
    maxofvalueString=parseFloat(valueString[0]);
    for(i=1; i <valueString.length; i++) 
    {
        if(maxofvalueString < parseFloat(valueString[i]) ) maxofvalueString = parseFloat(valueString[i]);
    }
    return maxofvalueString;
}

Open in new window

0
 
LVL 3

Author Comment

by:hernandez5999
ID: 41831155
I thought about parseInt and using maxvaluestring, you are correct on the index. Thanks I got it!
0
 
LVL 3

Author Closing Comment

by:hernandez5999
ID: 41831157
Thanks!
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Validating Date 4 28
ASP sending two datas 2 22
Link Anchor Not working 9 43
CSS - how to make button/link change to black on hover? 2 12
Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
This article discusses four methods for overlaying images in a container on a web page
In this tutorial viewers will learn how to position items using CSS's three positioning types Create a new HTML document with an internal stylesheet.: Create another div in CSS and name it Absolute : Type "position:absolute;" and "top:10px; left:50p…
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question