dotty Posted May 12, 2017 Share Posted May 12, 2017 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> Link to comment Share on other sites More sharing options...
dsonesuk Posted May 12, 2017 Share Posted May 12, 2017 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++) { Link to comment Share on other sites More sharing options...
Ingolme Posted May 12, 2017 Share Posted May 12, 2017 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 More sharing options...
dotty Posted May 13, 2017 Author Share Posted May 13, 2017 Could you re write it for me? so I can see how it is done ? thank you ! Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now