Jump to content

input value as an incremental number in a for loop


Recommended Posts

I do not get  the input value x to add to i in the for loop. What am I doing wrong?


<!DOCTYPE html>

<input id="inp" type="number" > </input>
<button type="button" onclick=myFunction() > click</button>
<p id="result" > </p>


function myFunction(){
     var txt= "";
     res = document.getElementById("result");
    var x= document.getElementById("inp").value;
    var i= 0;
    for (  ; i < 20; i++) {
        txt += "input" + i + "<br>";
        i = i += x ;
    console.log(txt += "input is " + (i+x) + "<br>");


Link to comment
Share on other sites

The parameters in the for loop are optional.

There are several ways to solve the problem. You can add the x right before appending to the string:

txt += "input" + (i + x) + "<br>";

You should cast x to a number before the loop to prevent it from being used as a string.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...