Paragraph disappears quickly after executing function

Asked

Viewed 30 times

0

Hello, I would like help with my code, I’m starting in js. I would like to show an arithmetic progression, but when I run the function by clicking the button, the answer shown in the paragraph with the id "pa" quickly disappears.

How to solve?

        function mostrar_Pa(){
            var a1 = Number(document.getElementById("a1").value);
            var r = Number(document.getElementById("r").value);
            var pa = "{" + a1;
            var an = a1+r;
            for(i = 0; i<10; i++){
            pa += ", " + an; 
            an += r;
            }
        document.getElementById("pa").innerHTML = pa + "}";
        }
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>PROGRESSÃO ARITMÉTICA</title>
</head>
<body>
    <form>
        Razão: <br><input type="number" id="r"><br>
        A1: <br><input type="number" id="a1"><br><br>
        <button onclick="mostrar_Pa();">Calcular PA</button>
    </form>
    <br>
    <p id="pa"></p>
    </body>
</html>

1 answer

1


You haven’t declared your kind <button>. Like he’s inside a <form>, the button ends up becoming the type submit, which means that when you click on it, the form is sent and a new page is loaded.

For the form not to be sent, declare the type of your button:

<button type="button" onclick="mostrar_Pa();">Calcular PA</button>
  • The answer is very clear. If you would like to add the answer: https://www.w3.org/TR/2011/WD-html5-20110525/the-button-element.html#the-button-element

Browser other questions tagged

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