Javascript loop for problem

Asked

Viewed 95 times

2

I want the loop below is show all even numbers that are smaller or equal to it, but I can only make it show the last number. If I type 40 and it returns only 2.

<div class="calculo">
    <input type="number" id="num1" placeholder="Informe o primeiro número: ">
    <button onclick = "pares()">Numeros Pares</button>
    <div id="resp"></div>

    <script>
        function pares(){
            var result = "";
            var num1 = parseInt (document.getElementById ("num1").value);
            for (num1 / 2 == 0; num1 > 0; num1 = num1 - 2) {
                document.getElementById("resp").innerHTML = num1;
            }
        }
    </script>
</div>

1 answer

1


The first expression of for is generating a boolean value, so it does not serve as an initializer. Initialization should consider whether the number typed is even or not, being odd should decrease 1 of the variable to make it even and facilitate accounts.

Another problem is that it is replacing the value in div, then only the last remains, have to keep adding each result.

function pares() {
    var num1 = parseInt(document.getElementById("num1").value)
    for (num1 -= num1 % 2; num1 > 0; num1 -= 2) document.getElementById("resp").innerHTML += num1 + "<br>";
}
<input type="number" id="num1" placeholder="Informe o primeiro número: ">
<button onclick = "pares()">Numeros Pares</button>
<div id="resp"></div>

I put in the Github for future reference.

Browser other questions tagged

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