inherit
205394
0
Jun 13, 2017 7:38:38 GMT -8
crystalfrost
55
February 2014
crystalfrost
|
Post by crystalfrost on Aug 15, 2014 4:20:10 GMT -8
I'm not sure where I can post this, so if it's in the wrong place someone please move it. I just need some coding help.
I'm extremely new to JavaScript, and I've been messing around with trying to create a random generator. I want to be have two inputs (a min and a max), and then have the function return a number between the two (inclusive for both).
<script> function random() { var x, text; x = document.getElementById("min").value; var y, text; y = document.getElementById("max").value; var z = document.getElementById("numb") z.innerHTML = Math.floor((Math.random() * (y - x)) + x); } </script>
<p>Please input a min and a max:</p>
<input id="min" type="text"> <input id="max" type="text">
<button type="button" onclick="random()">Submit</button>
<p id="numb"></p>
If I put in 5 and 10, it starts spitting out numbers less than five. Can someone tell me where I went wrong?
Oh, and here's the link to the page. all-around-rp.proboards.com/page/test
|
|
inherit
The Great Cinnamon Roll
191518
0
Oct 19, 2016 22:17:44 GMT -8
David Clark
Care for some tai chi with your chai tea?
17,602
March 2013
davidlinc1
|
Post by David Clark on Aug 15, 2014 8:52:47 GMT -8
I moved this over to the plugins section
|
|
inherit
162752
0
Nov 7, 2024 3:58:23 GMT -8
Pebble
Where it all does or doesn't happen!
1,437
January 2011
pebbleleague
|
Post by Pebble on Aug 15, 2014 13:20:38 GMT -8
This should work for you : <script> function random() { var x, text; x = parseInt(document.getElementById("min").value); var y, text; y = parseInt(document.getElementById("max").value);
var z = document.getElementById("numb") z.innerHTML = Math.floor((Math.random() * (y - x)) + x); } </script>
<p>Please input a min and a max:</p>
<input id="min" type="text">
<input id="max" type="text">
<button type="button" onclick="random()">Submit</button>
<p id="numb"></p> The value needs to be a number, so you need parseInt to do that. More info here : www.w3schools.com/jsref/jsref_parseint.aspEDIT: So it makes more sense! The x and y 'values' are returned as strings so you can use parseInt to convert x and y into numerical values..... Hope this helps!
|
|
inherit
205394
0
Jun 13, 2017 7:38:38 GMT -8
crystalfrost
55
February 2014
crystalfrost
|
Post by crystalfrost on Aug 15, 2014 14:19:46 GMT -8
Thank you! That worked perfectly.
|
|