Reputation: 69
I'm trying to create JS script that will generate random numbers between 2 values. But it doesn't work and I can't figure out why.
<form id="form" action="" method="get">
From: <input type="text" name="from" id="from"><br>
To: <input type="text" name="to" id="to"><br><br>
<button onclick="random_gen()">Generate</button>
</form>
<script>
function random_gen() {
var a = document.getElementById("from").value;
var b = document.getElementById("to").value;
var c = Math.floor((Math.random() * b) + a);
document.getElementById("final").innerHTML = c;
return false;
}
</script>
<p id="final"></p>
PS I'm new at JS
Upvotes: 0
Views: 549
Reputation: 1493
Edited to reflect the comment from @blex, which is correct
The correct algorithm for random is:
function rand(a,b){
return Math.floor(Math.random()*(b-a)+a);
}
When retrieving the values from an input, you must do parseInt:
var a = parseInt(document.getElementById("from").value);
var b = parseInt(document.getElementById("to").value);
Of course, you should check the values to make sure they are integers before you use them.
Upvotes: 3
Reputation: 239290
Your element's values will be strings. You're going to wind up with a weird number, because you're generating a random number with Math.random() * b
, which converts b
to a number, and then concatenating the string contained in a
to it.
Lets assume the following:
var a = '10';
var b = '20';
So, Math.random() * b
works fine. It gives you a value like 15.12345
. The problem is, you're concatenating the string "10"
to the result, giving you a string, 15.1234510
, which is passed to Math.floor
, and converted back to the number 15
.
You need to convert both of your inputs to numbers before passing them through your rand
process. Use parseInt
for this:
var a = parseInt(document.getElementById("from").value, 10);
var b = parseInt(document.getElementById("to").value, 10);
Upvotes: 0