Pergunta

When I click the roll button, nothing happens. Is there a way to show the results using document.getElementByID("results").innerHTML, or is this not recommended?

HTML

<p>How many dice?
    <br/>
    <input type="text" id="numDice" />
</p>
<p>How many sides per die?
    <br/>
    <input type="text" id="numSides" />
</p>
<button onclick="diceRoll()" id="roll"/>Roll!</button>
<p id="results"></p>

JavaScript

var numDice = document.getElementByID(numDice).innerHTML;
var numSides = document.getElementByID(numSides).innerHTML;

function diceRoll() {
  var results = "";

  for (var i = 0; i < numDice; i++) {
    results += (Math.random() * numSides) + 1;
  }

  document.getElementByID("results").innerHTML = results;
}

CodePen

Foi útil?

Solução

Typo, it's not

getElementByID

but

getElementById

The case is important, and the arguments passed are strings, so they should be quoted

function diceRoll() {
    var numDice = document.getElementById('numDice').value;
    var numSides = document.getElementById('numSides').value;
    var results = "";

    for (var i = 0; i < numDice; i++) {
        results += (Math.round(results + (Math.random() * numSides) + 1)).toString();
    }

    document.getElementById('results').innerHTML = results;
}

FIDDLE

Outras dicas

You are calling document.getElementByID(numDice).innerHTML before the DOM is ready. The element does not exist, so this will throw an error.

You want to get the values each time diceRoll() is called, so that you get the values the user entered. numDice will not automatically update when the value changes.

P.S. It's getElementById, and you want to use .value() for <input>s.

function diceRoll() {
  var results = "";
  var numDice = parseInt(document.getElementById('numDice').value, 10);
  var numSides = parseInt(document.getElementById('numSides').value, 10);

  for (var i = 0; i < numDice; i++) {
    results += (Math.random() * numSides) + 1;
  }

  document.getElementById("results").innerHTML = results;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top