Solved

Statistic Calculator using Javascript

Posted on 2016-09-25
7
46 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 21

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 21

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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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 21

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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Someone recently asked me about how to display a progress indicator on a page while an iframe is loading. And I remember when I first came across this myself. It was a bit tricky to get my head around, but really, it's very simple. The most impor…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
In this tutorial viewers will learn how to style a corner ribbon overlay for an image using CSS Create a new class by typing ".Ribbon":  Define the class' "display:" as "inline-block": Define its "position:" as "relative": Define its "overflow:" as …
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…

707 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now