Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Statistic Calculator using Javascript

Posted on 2016-09-25
7
94 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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
In this Micro Tutorial viewers will learn how to create navigation buttons that change on rollover, using CSS (Continuation of the CSS Image Sprite tutorial) Create a parent ID for all the list items       - Specify position: absolute and display: block…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

829 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