-
JavaScript assistance
I am looking for help in creating a page that rolls six-sided dice. The user should be able to type the number of dice to roll and when he/she clicks a button, JavaScript will roll the dice and tell how many of each number (1 through 6) came up. Use a form to give this information to the user.
Many thanks.
-
Hey,
What you're basically doing is creating a random number from 1-6. To do this, you usually go:
Math.floor(Math.random()*greatestValue)+lowestValue
Math.random() produces a result 0-1. So, in your case, it should be:
Math.floor(Math.random()*6)+1
So, we can use this information to do what you want:
Code:
<script>
function rollD(frm){
x=parseInt(frm.input1.value);
result=new Array(x);
for(i=0;i<x;i++){
result[i]=Math.floor(Math.random()*6)+1;
}
frm.res.value=result.join(", ");
}
</script>
<form>
Dice to roll: <input type="text" name="input1"> <input type="button" value="Roll!" onclick="rollD(this.form)">
<br>Result of the dice: <input type="text" name="res">
</form>
aDog :cool: