samedi 3 mars 2018

JavaScript: Generating a Random Number According to User Input

I wish to build a very simple web page which generates a random number (integer) corresponding to three parameters provided by the user:

  1. A bottom limit number (the output can't be smaller than this number).
  2. An upper limit number (the output can't be bigger than this number).
  3. A value between 1 and 9 that defines the number of digits composing the number (length). For example, if the number was set to be anywhere between 1 and 999, this parameter will define whether the resulting number will be somewhere between 1 and 9, 10 and 99, and 100 and 999.

So far, this is what I have:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<form name="settings">

How many numbers should be generated? <input type="number" min="1" max="6" name="numbers"/>
<br/>
Smallest number in the range <input type="number" min="1" max="999998" name="lownum"/>
<br/>
Biggest number in the range <input type="number" min="2" max="999999" name="highnum"/>
<input type="submit" onclick="validate()">

</form>

<script>

function validate(){
if(parseInt(document.settings.lownum.value)>parseInt(document.settings.highnum.value))
    {
        alert("!");
    }
    else
        {
            alert(generator());
        }
}

function generator() {
    var min = parseInt(document.settings.lownum.value);
    var max = parseInt(document.settings.highnum.value);
    return Math.floor(Math.random() * (max - min +1)) + min
}
</script>



</body>
</html>

I think I got the lower/upper limit figured out, but I can't say the same regarding the number of digits.

Thanks!




Aucun commentaire:

Enregistrer un commentaire