David Lee
David Lee

Reputation: 601

How to increment a value in Javascript with a value the user defines

I want to write a loop that will display numbers from 1-100 in multiples that the user picks.

Here's my JS code.

 var x = prompt("Enter the increment you want to see")

   for (i=0;i<=100;i=i+x) {
    document.write(i+"</br>")
   }

For example, if I enter "10" I want the code to print the numbers 10, 20,30,40,50,60,70,80,90,100

Why does this not work?

I am teaching myself Javascript, and I am going crazy trying to figure this out.

Can anyone help?

Upvotes: 0

Views: 516

Answers (2)

eladcon
eladcon

Reputation: 5825

The returned value from prompt is string. You need to parse it as a number (with the radix value as stated in the comments):

var x = parseInt(prompt("Enter the increment you want to see"), 10);

Upvotes: 3

Aswin Ramakrishnan
Aswin Ramakrishnan

Reputation: 3213

You need to parse x. The following code should work -

var x = parseInt(prompt("Enter the increment you want to see"));

for (i = 0; i <= 100; i = i + x) {
  document.write(i + " </br>");
}

Upvotes: 1

Related Questions