I am trying to display two outputs in different functions into single innerHTML when the button clicked. However, I want it without using a global variable to store the output. I have tried using array for storing the string output, however, the error is whether the output is not displayed correctly or it will keep storing the string output when I used push() to store output inside the array
The HTML:
<div>
<button type="button" id="display">display</button>
<button type="button" id="stats">stats </button>
<p id="msg"></p>
</div>
The Script:
//declare global array
var array = [1,2,3];
function list(){
var output ="";
var i;
for (i =0; i < array.length; i++){
output = output + " " + array[i];
}
//this output will be displayed when the first button is clicked
output = "List of all values in the array: <br>" + output + "<br>";
document.getElementById("msg").innerHTML = output;
}
function stats(){
var output = "";
var sum = 0;
var i;
for (i = 0; i < array.length; i++) {
sum += array[i];
}
output = output + "The number of values in the array: " + array.length + "<br>The total of all values in the array: " + sum;
//here I want to display the output of list() function + stats()
//when the second button is clicked
document.getElementById("msg").innerHTML = output;
}
function init() {
var btnList = document.getElementById("display");
var btnStats = document.getElementById("stats");
btnList.onclick = list;
btnStats.onclick = stats;
}