Jump to content
dotty

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>
<html>
<body>

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

 

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

</script>
</body>
</html>

Share this post


Link to post
Share on other sites

for loop has 3 parameters start;condition;increment

So

var i= 0;
    for (  ; i < 20; i++) {

should be

for (var i= 0; i < 20; i++) {

 

Share this post


Link to post
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.

Share this post


Link to post
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

×