Problem with loop for in JavaScript

2

I want the loop below to show all even numbers that are less than or equal to it, but I can only get it to 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>
    
asked by anonymous 26.03.2018 / 06:59

1 answer

1

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

Another problem is that you are replacing the value in div , so only the last one remains, you have to add 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>
    
26.03.2018 / 07:15