daveC
daveC

Reputation: 23

Creating a random number generating using user inputted number range. (JavaScript)

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.

Upvotes: 2

Views: 87

Answers (3)

Aral Roca
Aral Roca

Reputation: 5909

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);
}

Upvotes: 0

thatOneGuy
thatOneGuy

Reputation: 10612

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()">

Upvotes: 2

glcheetham
glcheetham

Reputation: 1003

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));
}

Upvotes: 0

Related Questions