Brian Smith
Brian Smith

Reputation: 1481

Random number between variables issue

I've seen the other examples on this site but I just can't get it to work.

I'm trying to generate a random number between 2 user input variables on a form. The numbers will always be positive numbers.

min = document.getElementById('min').value;
max = document.getElementById('max').value;
waitTimer = Math.floor(Math.random() * (max - min + 1)) + min;

When min = 5 / max = 10, waitTimer is sometimes returning results like 2, 4 and 28 and so on.

What am I doing wrong?

Upvotes: 0

Views: 357

Answers (2)

jfriend00
jfriend00

Reputation: 707208

You have to convert the .value strings to numbers (I just used the + operator for the conversion in my jsFiddle).

When you convert them to numbers, it all works fine as you can see here: http://jsfiddle.net/jfriend00/XF75E/

Upvotes: 0

user1707309
user1707309

Reputation: 81

Here is a fiddle of this working. Make sure you are using parseInt()

http://jsfiddle.net/zAeR7/2/

You just need to put a number in each input and click off the input (or press tab) and it should update the random number.

Upvotes: 2

Related Questions