Search code examples
javascripthtmlfunctionbuttonclick

How to show the total increment of an app counter


Guys I wanna make an app which can count people, I have it according to the course but I'd like to add the total at the end not the previous entries.

enter image description here



let saveEl = document.getElementById("save-el")
let countEl = document.getElementById("count-el")

let count = 0

function counter() {

    count += 1
    countEl.textContent = count

}

function save()   {

    //let countStr = count + "-" caso eu não queira que volte do zero

    let countStr = count + " - "

    saveEl.textContent += countStr 

    countEl.textContent = 0

    count = 0

}



console.log(count)

Solution

  • Instructions were not clear but I guess you want to "sum up the counts" instead of displaying them separately.

    Here's a codepen achieving that, hopefully that works for you ;)

    let saveEl = document.getElementById("save-el")
    let countEl = document.getElementById("count-el")
    
    let count = 0
    
    function counter() {
        count += 1
        countEl.textContent = count
    }
    
    function save() {
        let prevCount = saveEl.textContent ? parseInt(saveEl.textContent) : 0
        saveEl.textContent = count + prevCount
    
        countEl.textContent = 0
        count = 0
    } 
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Counter</title>
    </head>
    <body>
      <h1>Members :</h1>
      <button onClick=counter()>counter</button>
      <button onClick=save()>save</button>
      <p id="count-el"></p>
      <hr/>
      <p id="save-el"></p>
    </body>
    </html>