+ 3

Getting input value as a character instead of an integer

I'm having some troubles with js. I'm trying to generate a random number between a specified range, but the code treats the number generated by Math.random as a character. So that for example: Set a range between 2 and 13, I should get, say, 7. But all I get is 72 because in the variable "translated", the two characters 7 and 2 (minimum value of the range) are put together to make a string. Here's the code: function gen() { var min = document.getElementById("min").value; var max = document.getElementById("max").value; var range = max - min; var random = Math.ceil(Math.random()*range); var translated = random + min; document.getElementById("result").innerHTML = translated; } Any suggestion?

2nd Jan 2018, 6:36 PM
Luca Marseglia
Luca Marseglia - avatar
2 Réponses
+ 5
min and max are both strings, so you'll need to parseInt() their value first. var max = parseInt(document.getElementById('max').value); var min = parseInt(document.getElementById('min').value);
2nd Jan 2018, 8:03 PM
The Coding Sloth
The Coding Sloth - avatar
+ 1
Thank you very much. Here's the final code: https://code.sololearn.com/WC2zUi4mjUIz
2nd Jan 2018, 8:39 PM
Luca Marseglia
Luca Marseglia - avatar