2

I am trying to create a random number game. One of the elements that I need is a random number generator that allows the user to set the range of which the number will be chosen from. Currently I have this and it does not work. Any tips?

JavaScript

var min = document.getElementById("minNum").value;
var max = document.getElementById("maxNum").value;

function setRandomNum() {
document.write(Math.floor(Math.random() * (max - min));
}

HTML

<input type="text" id="minNum" name="minNum" />
<input type="text" id="maxNum" name="maxNum">
<input type="button" id="submitRange" name="submitRange" value="Set Range" onclick="setRandomNum()">

For now the document.write is there just to test if it works.

3 Answers 3

2

You're getting the values of the inputs on document load i.e not when the button is pressed and as mentioned in the comments, value is a string so you have to parse it like so :

function setRandomNum() {

  var min = parseInt(document.getElementById("minNum").value);
  var max = parseInt(document.getElementById("maxNum").value);
  var randomNum = Math.floor(Math.random() * (max - min))
  document.write(randomNum);
}
<input type="text" id="minNum" name="minNum" />
<input type="text" id="maxNum" name="maxNum">
<input type="button" id="submitRange" name="submitRange" value="Set Range" onclick="setRandomNum()">

Sign up to request clarification or add additional context in comments.

10 Comments

You may also want to mention that the value is a string, not a number, and use a radix to ensure a decimal number...
@thisOneGuy So in addition to the code above, would I have to do something like create a new variable such as this? var randomNum = parseFloat(setRandomNum);
what are you trying to do ? I think i see. Just do var randomNum = Math.floor(Math.random() * (max - min)); ill append to answer
@thisOneGuy Sorry, I'm a bit new to javaScript. But I was trying to ensure a number like David Thomas said. So, would the code that was added suffice?
The subtracting, (max - min), will force the string to be parsed as an integer regardless.
|
0

Your calls to document.getElementById are outside the function, so they are not executed in time.

function setRandomNum() {
    var min = document.getElementById("minNum").value;
    var max = document.getElementById("maxNum").value;
    document.write(Math.floor(Math.random() * (max - min));
}

Comments

0

I voted for thisOneGuy solution. But I recommend to put the getElementId outside the function for performance:

var minElement = document.getElementById("minNum");
var maxElement = document.getElementById("maxNum");

function setRandomNum () {
  var max, min, random;

  max = parseInt(maxElement.value);
  min = parseInt(minElement.value);
  random = Math.floor(Math.random() * (max - min));

  document.write(random);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.