Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to prevent innerHTML repeating the previous value

I’m a JS learner and want to create an app that will calculate the average from input values. So far I’ve managed to push the entered input values into an array. However, when I want to display them, the previous value is repeated. So I’m near the end. But now I’m stuck. Can you lend me hand with that?

        Enter
      </button>
      <p id="numbersEntered"></p>
      <button id="avg" type="button">Average</button>
      <p id="average"></p>
  
   let numbersEntered = document.querySelector("#numbersEntered");
   let inputEl = document.querySelector("#input");

   // buttons
   let enter = document.querySelector("#enter");

   let numArr = [];

   enter.addEventListener("click", displayNums);

   function displayNums() {
   let newNumber = inputEl.value;
   numArr.push(newNumber);
   console.log(numArr);

   for (let i = 0; i < numArr.length; i++) {
    numbersEntered.innerHTML += numArr[i] + ",";
  }
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can just clear the innerHTML before appending;

function displayNums() {
   let newNumber = inputEl.value;
   numArr.push(newNumber);
   numbersEntered.innerHTML = "";  //Clear the innerHTML
   for (let i = 0; i < numArr.length; i++) {
     numbersEntered.innerHTML += numArr[i] + ",";
   }
}

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading