how do I create a button to increment one more

Asked

Viewed 35 times

-1

Good morning, I’m new with javascript and I’m having a hard time creating a button where mine always changes my H2 to +1, follow my code:

<body>
    <script src="script.js"></script>
    <h1 style="text-align: center;">SENHA</h1>
    <h2 style="text-align: center;">0</h2>

    

    <div style="text-align: center;">
    <button id="count" >Nova Senha</button>
    </div>
    <br>

    <form style="text-align: center;"><input type="button" value="IMPRIMIR" onClick="window.print()"/></form>
</body>
</html>

var cont = 0; Function counter(){ Let button = Document.getElementById("btn"); Let H2 = Document.getelementsbytagname("H2");

    cont++;

}

I need 0 to start adding +1 every time I click on a new password, someone knows what I have to do to fix the code ??

  • The function contador is not called in your code; and if it is, only changes the variable cont, not used in the code.

  • What do you mean it’s not called in my code? I call it in the <script>

  • In the code that posted in the question it is not called. If it really is in your code, I ask you to elaborate then a [mcve] demonstrating the problem

1 answer

0


Your code should look like this:

<body>
    <h1 style="text-align: center;">SENHA</h1>
    <h2 id="count" style="text-align: center;">0</h2>

    <div style="text-align: center;">
    <button onclick="contar()">Nova Senha</button>
    </div>
    <br>

    <form style="text-align: center;"><input type="button" value="IMPRIMIR" onClick="window.print()"/></form>

    <script>
        let count = 0
        const countElement = document.getElementById("count")
        
        function contar() {
            count++
            countElement.textContent = count
        }
    </script>
</body>
</html>

Beauty but what was your mistake?

You simply took the button and the H2 but did NOTHING with them. You should have put on the button the action of contador in the onclick because if it won’t happen when?

Another thing after making the function be called you have to put the value of the counter in your H2. Then you do h2.textContent = ValorQueTuQuer and automatically html will update with this new value.

var cont = 0;
function contador(){
        let button = document.getElementById("btn");
        let h2 = document.getElementsByTagName("h2");
        
        cont++;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.