0

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;
}

1 Answer 1

1

It's simple just call list() inside stats() and then append the innerHTML.

The updated Script

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>"; 
  debugger;
  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
  list();
  document.getElementById("msg").innerHTML += output;
}

function init() {
  var btnList = document.getElementById("display");
  var btnStats = document.getElementById("stats");
  btnList.onclick = list;
  btnStats.onclick = stats;
}

init();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.