Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    New to the CF scene
    Join Date
    Dec 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How to add numbers from an array, based off of user input?

    This is my first time using this site so please excuse the unclean post.
    Red shows the main important portion of the code.
    Blue shows the specific area in which I am struggling.

    My number one issue is that I can not add together all of the numbers that the user puts into the array. I have tried in every way but I simple do not understand how to take the users inputted numbers, and add them up in the array. Because every time a new number is submitted my code only takes that number rather than adding the new number AND the previous numbers.

    Any help is much appreciated! Thank you!




    [CODE]
    <!DOCTYPE html>
    <html>
    <head>
    <title>Student Scores Calculator</title>
    </head>

    <body>
    <div>
    <h1>Chapter 5 Array Assignment 2</h1>
    <p>Score:<input type="text" style="text-align:left" id="txtScore" />
    Scores:<textarea id="txtListOfScores" disabled="disabled" style="width:200px; height: 150px; float: right;"></textarea></p>
    <p>Score Total:<input type="text" style="text-align:left" id="txtScoreTotal" disabled="disabled"/></p>
    <p>Score Count:<input type="text" style="text-align:left" id="txtScoreCount" disabled="disabled"/></p>
    <p>Average:<input type="text" style="text-align:left" id="txtAverage" disabled="disabled"/></p>
    <p><input type="button" id="btnAddStudentScore" value="Add" />
    <input type="button" id="btnClearStudentScores" value="Clear" /></p>
    </div>



    <script type="text/javascript">

    var $ = function (id) {
    return document.getElementById(id);
    }

    window.onload = function () {
    document.getElementById("btnAddStudentScore").onclick = btnAddStudentScoreClick;
    document.getElementById("btnClearStudentScores").onclick = btnClearStudentScoresClick;
    };





    var students = [];

    function btnAddStudentScoreClick() {
    var studentScore = txtScore.value;
    var student = [];


    check = $("txtScore").value;

    if (isNaN(check))
    {
    alert("Please enter numbers only.");
    ClearAndMouse();
    return
    }

    else {
    $('txtListOfScores').innerHTML = "";

    student = new Array();
    student["Score"] = studentScore;
    students.push(student);

    for (var i = 0; i < students.length; i++) {
    WriteMessage("<br/>" + students[i]["Score"]);


    var total = [parseInt(students[i]["Score"])].reduce(function(a, b) {
    return a + b;
    });


    }


    $('txtAverage').value = total;

    $('txtScoreTotal').value = total;

    $('txtScoreCount').value = i;
    ClearAndMouse();
    }
    }






    function btnClearStudentScoresClick() {
    $('txtListOfScores').innerHTML = "";
    ClearAndMouse();
    students.length = 0;
    $("txtScoreCount").value = "";
    }

    function WriteMessage(message) {
    $('txtListOfScores').innerHTML += message;
    }

    function ClearAndMouse() {
    $("txtScore").value = "";
    $('txtScore').focus();
    }


    </script>
    </body>
    </html>
    [CODE]

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,310
    Thanks
    203
    Thanked 2,563 Times in 2,541 Posts
    var student = [];
    student = new Array();

    You are declaring the array within the function, so each time the function executes the contents of the array are erased and a new blank array is created. In fact you are creating two arrays with the same name, one with the var keyword which is local to the function and one without the var keyword which creates another array of the same name in the global scope.

    The closing code tag is /CODE.

    All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

    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.

  • #3
    New to the CF scene
    Join Date
    Dec 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I dont think thats necessarily true. Because everytime I click the add button. It displays all of the previous contents of the array in the text area. For example: If i inputted 50, 65, 82 one at a time into the text field. Everytime I click the add button it will display the currently typed number and the previously entered numbers. But for some reason I cannot access those numbers in order to sum them up.

    What exactly are you suggesting me to do, I didnt fully understand your directions?

    Also, is there a proper way to add the contents?

    Please excuse my many questions I am relatively new to Javascript coding

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,310
    Thanks
    203
    Thanked 2,563 Times in 2,541 Posts
    I don't see any textarea in your code.

    I have told you what is wrong, but if you won't accept that then that is your problem.

    In principle, the way to add a series of numbers in an array is

    Code:
    var myArray = [];  // declare the array once
    var total = 0;  // initialise total
    for (var i =0; i<myArray.length; i++) {
    total += myArray[i];  // add each array element to total
    }
    Note that the array declaration var myArray = [];
    must be executed by the program only once.
    Last edited by Philip M; 12-11-2013 at 06:18 PM.

    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.

  • #5
    New to the CF scene
    Join Date
    Dec 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Actually if you look, there is indeed a text area.

    And no need to be rude, its not that I dont ""Accept" your explanation. Its that I dont understand it/ its not working for me.

    And I have taken your suggestions and it is still only displaying the most previously entered number rather than adding it with all of the numbers.

    Thanks anyway.

  • #6
    Regular Coder Vincent Puglia's Avatar
    Join Date
    Jul 2003
    Location
    where the World once stood
    Posts
    367
    Thanks
    0
    Thanked 13 Times in 13 Posts
    HI,

    works for me
    Code:
    	
    theArray = new Array();
    			for (var i = 0; i < students.length; i++) {
    				WriteMessage("<br />" + students[i]["Score"]); 
    theArray.push(parseInt(students[i]["Score"]))
    				var total = theArray.reduce(function(a, b) {
    alert('a ' + a + ' b ' + b + ' a+b ' + (a+b) )
    					return a + b;
    				}); 
    	alert('total ' +total)
    Where the world once stood
    the blades of grass
    cut me still


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •