Statistic Calculator using Javascript

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,
LVL 3
Jose Rivera-HernandezAVP of ISAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kim WalkerWeb Programmer/TechnicianCommented:
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.
Jose Rivera-HernandezAVP of ISAuthor Commented:
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.
Kim WalkerWeb Programmer/TechnicianCommented:
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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Jose Rivera-HernandezAVP of ISAuthor Commented:
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,
Kim WalkerWeb Programmer/TechnicianCommented:
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

Jose Rivera-HernandezAVP of ISAuthor Commented:
I thought about parseInt and using maxvaluestring, you are correct on the index. Thanks I got it!
Jose Rivera-HernandezAVP of ISAuthor Commented:
Thanks!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.