-1

So I'm trying to create a random number generator in html using javascript to randomise and alert the user of the number generated. However I always get an error when getting my number which I don't experience when using codecademy. The code is:

<input type="button" value="Enter" id="enter"
onClick="alert(getRandomInt(document.getElementById('min').value,
document.getElementById('max').value));">
</div>
<script type="text/javascript">
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

When 5 and 10 are input as min and max numbers respectively,for example,the resulting numbers are 15,25,05,35 etc. The first digits apparently is found using the function

Math.floor(Math.random() * (max - min + 1))

and the last digit would be the number 5 which is the minimum. So I was wondering if anyone could teach me how to put the + min into the entire operation so I can get a number within the range of 5-10? Thanks in advance

Zachary
  • 43
  • 5
  • 1
    `However I always get an error when getting my number` what is the error? – VLAZ Oct 13 '16 at 07:06
  • What is the error ? – Alexis Oct 13 '16 at 07:07
  • 1
    Try `parseInt()` on values you read from elements `max` and `min` – augur Oct 13 '16 at 07:08
  • 1
    One issue you'll have is that `value` is always a string, you need to parse your numbers. But that wouldn't cause an *error*, just unexpected output. – T.J. Crowder Oct 13 '16 at 07:08
  • @T.J.Crowder oh ok sorry if I was being unspecific. I just saw it as an error when it is actually unexpected. Also sorry for making a duplicate as I'm quite new to coding and I don't really know the keywords around here – Zachary Oct 13 '16 at 13:44

1 Answers1

1

min is a string and by adding, you add a string, with subtraction the value is casted to Number.

You could add another + sign in front of min, that cast the value to Number

return Math.floor(Math.random() * (max - min + 1)) + +min;
//                                                  ^^^
sabithpocker
  • 15,274
  • 1
  • 42
  • 75
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392