I’m brand new to JavaScript, and I’m trying to create a dice roller. The user can choose the number of dice and the number of sides on the dice. I’d like to have the individual dice results displayed on the webpage. My JS is
howManySides = Number(document.getElementById('howManySidesInput').value);
howManyDice = Number(document.getElementById('howManyDiceInput').value);
document.getElementById('submitButtonDice').onclick = function() {
for(let i = 1; i >= howManyDice; i += 1){
var roll = ((Math.floor(Math.random() * howManySides)) + 1);
document.getElementById('diceResultIndividual').innerHTML += roll + " ";
}
}
I expected the results of each die roll to be added to my HTML document, but there’s no output at all. I tried console.log(roll)
between lines 6 and 7, hoping to see an error in the console, but I’m getting nothing. What am I doing wrong?
2
Answers
There is a small mistake in your loop condition. The condition i >= howManyDice will always be false. You should change the condition to i <= howManyDice. and it will work fine.
and your console was clear because your for loop is never been executed.
First, you should check if the loop is not being run or if the entire function is not being run.
Try something like this:
Another thing I want to add is in your loop the 2nd parameter is slightly wrong. Instead of >= you should add <=. This is because the second parameter is the one that checks if the loop should keep running and if i >= howManyDice, then it will keep going till infinity, which could be the problem here.
So the overall code that should be tested is: