Home > Back-end >  I want to make Random number generator in javascript/html
I want to make Random number generator in javascript/html

Time:01-07

So basically i want to do is accept two values

var a,b;

and then put them in max and min for random number generator

 let x = Math.floor((Math.random() * 10)   1);
 document.getElementById("demo").innerHTML = x; 

How do I get the values 10 and 1 be var a and b;

<!DOCTYPE html>
<html> 
<head>
<title> TEST </title> 
<script type="text/javascript">
function random()
{
var a,b; 
a=parseInt(form.v1.value);
b=parseInt(form.v2.value);
}

I have made this code for accepting values now how to i input them into max and min for my random number generator

CodePudding user response:

Here is an example of how you could do this.

For a real application though, it is important to validate the input of the user before using it in your code. For example you should check if the maximum is higher than the minimum, if no malicious code is inserted etc.

    btn = document.getElementById("button");

    btn.addEventListener("click", () => {
      minInput = document.getElementById("min");
      maxInput = document.getElementById("max");

      min = Number(minInput.value);
      max = Number(maxInput.value);

      randomNumber = document.getElementById("random-number");

      randomNumber.textContent = Math.floor(
        Math.random() * (max - min   1)   min
      );
    });
  <body>
    <h1>Random number generator</h1>
    <div style="display: flex; flex-direction: column; max-width: 300px">
      <label for="max">Type your minimum here</label>
      <input type="number" id="min" />
      <label for="min">Type your maximum here</label>
      <input type="number" id="max" />
      <button id="button">Generate random number</button>
      <h2 id="random-number" style="text-align: center">...</h2>
    </div>
  </body>

CodePudding user response:

 let x = Math.floor((Math.random() * 10)   1);

Basically this line create a random number between 1 and 10, ...

Now let us define a function to make it simple

function randomGen(min, max){
   let result = Math.floor((Math.random() * max)   min);
   return result
}

To get the value of a and b

To get the value of a and b you can use onclick event in a form that call your function

<button onClick="yourFunction()"> Create random </button>
  • Related