Jelles Duin Jelles Duin - 1 month ago 6
Javascript Question

Loop i dont know what to do

I am trying to make it when i press the button and there is 5 in the text box it will alert the square number for 1 to 5 so like this
square number for 1 = 1
square number for 2 = 4
square number for 3 = 9
square number for 4 = 16
square number for 5 = 25
and when the number is 7 etc but when the number is over 20 it will make an error can you guys please help me thanks!

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function kwadraat(){
var text = "";
var i;
var t = parseFloat(text2.value)
var numm = t + 1
for (i = 1; i < numm; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}

</script>

</head>
<body>
Test<br>
<input type="text" id="text2">
<p id="demo"></p>
<button onClick="kwadraat()">Test</button>
</body>
</html>

Answer

You was nearly there.

I've basically restructured your code a little, added the condition for more than 20.. Also you was using parseFloat, it's obviously not a float your wanting to parse, so changed it to parseInt.

<!DOCTYPE html>
    <html>
    <head>
        <title>Test</title>
        <script type="text/javascript">
        function kwadraat(){
            var text = "", i,
                t = parseInt(text2.value, 10),
                demo = document.getElementById("demo"),
                numm = t;
            if (numm > 20) {
                demo.innerHTML = 'Too Big!!!';
                return;
            }
            for (i = 1; i <= numm; i++) {
                text += "The number is " + i + "="+ (i*i) +"<br>";
            }
            demo.innerHTML = text;
        }
        </script>
    </head>
    <body>
    Test<br>
    <input type="text" id="text2">
        <p id="demo"></p>
        <button onClick="kwadraat()">Test</button>
    </body>
    </html>