ochj1ch ochj1ch - 1 year ago 95
HTML Question

random number js min max

I'm trying to get random number between 2 numbers from input in JavaScript. When I put numbers instead of max.value and min.value it works, but not with variable. I can't understand how does random in js work, in other programming languages I know it's easy done like random(min,max) so I totally don't understand why is it so hard in JS. Thank you.

function genRanNumb() {

<input type="text" id="min">
<input type="text" id="max">
<button id="btn" onclick="genRanNumb()">button</button>
<p id="demo"></p>

Answer Source

I think the matter is your inputs are text and your random wants int values The solution is to surrond your variable with parseFloat(yourvariable) in javascript.
in your case you have :

function genRanNumb() {

Hope it answer to your question.

For better readability and best compatibility, you should write it like this:

function genRanNumb() {
  var max = parseFloat(document.getElementById("max").value,10),
      min = parseFloat(document.getElementById("min").value,10);