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>");


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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...