5

We have a form with 2 fields and a button. We want on button click to output random int number (like 3, 5 or 33) which would lie between int A and int B? (no use of jQuery or anything like it is required)

Rella
  • 62,177
  • 103
  • 350
  • 621

3 Answers3

12

You can use Javascript Math.random

function randomInRange(start,end){
       return Math.floor(Math.random() * (end - start + 1) + start);
}
Samet Atdag
  • 982
  • 6
  • 21
3

Use something like Math.floor(Math.random()*(intB-intA +1)) + intA ?

ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
Sebastiaan van den Broek
  • 5,262
  • 5
  • 35
  • 68
2

Like this:

Math.floor(a + Math.random() * (b - a))

The Math.random() method returns a random floating-point number in the range [0,1) — that is, between 0 (inclusive) and 1 (exclusive).

Zsolt Meszaros
  • 15,542
  • 12
  • 36
  • 40
SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933