Problem to combine 2 separate scripts properly

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mattkrebs
    New Member
    • Sep 2019
    • 5

    Problem to combine 2 separate scripts properly

    1st piece of code allows me to use an alert to compile a list of grades:

    Code:
    <body onload="loadGrades()">
    <button onclick="myFunction()">Add a grade!</button>
    <p id="grades"></p>
    
    
    <script>
    var grades = [10,12,13];
    
    function loadGrades(){
    document.getElementById("grades").innerHTML =grades;
    
    }
    function myFunction() {
    var grade = prompt("what is the next grade?");
    grades[grades.length]=grade;
    
    document.getElementById("grades").innerHTML = grades;
    }
    
    </script>
    </body>
    2nd piece of code allows me to calculate the mean of a list of numbers but only when I manipulate the list from within the code:


    Code:
    <script>
    
    
    var Grades = [10,20];
    
    var sum=0;
    if(Grades.length>0){
    for(index=0;index<Grades.length;index++){
    
    sum+=Grades[index];
    }
    
    
    document.write(sum/Grades.length);
    
    document.write(" is the average of the following grades" + Grades);
    }
    else
    document.write("Emptyy");
    
    
    </script>
    I cannot figure out how to make the new list (when I enter a new number in the prompt) to automatically update the mean of the grades. I would have thought it would have been as easy as cutting and pasting the two parts together but I couldn't get it to work.

    Any thoughts wouild be appreciated!

    Thanks.
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    well first the array that contains the numbers for your calculation in the 2 script-snippets have different names - thus they are independent from each other when you just want to merge the snippets. But it wouldn't work either then - because you would need to recalculate when the input was made and the array was updated. So wrap the calculation and output of the result into another function as well and call it at the right place.

    Comment

    Working...