How to print function result on html body?

1.6k views Asked by At

I need to display the result of y on span.

Currently when I click on the play button it doesn't do anything for me. There might be more issues with my code.

What I need the function to do is to take the number user typed inside input box , convert it into int, and store it inside the "x". Y is to store the amount of time this loop happens. While x is bigger than 0, roll the dice and get the sum.

x+4 if sum is exactly 7, otherwise x-1. Everytime this function loops, x-1.

Thanks.

function playLoop() {
  var x = parseInt(document.getElementById("amount").val());
  var y = 0;
  while (x > 0) {
    var die1 = Math.floor((Math.random() * 6) + 1);
    var die2 = Math.floor((Math.random() * 6) + 1);
    if (die1 + die2 == 7) {
      x + 4;
    } else {
      x - 1;
    }
  }
  x--
  y++
  document.getElementById("result").innerHTML = y;
}
<div class="container">
  <label>Starting Bet:</label>
  <input id="amount" type="text">
  <button onclick="playLoop()">Play</button>
  <span id="result"></span>
</div>

2

There are 2 answers

0
Thomas Juranek On

You are using .val() which isn't a function, but .value() is.

var x = parseInt(document.getElementById("amount").value());
1
Barmar On

The way to get the value of an input element is with .value, not .val() (that's a jQuery method).

Your while() loop never ends because you never modify x during the loop. x + 4 should be x += 4, and x - 1 should be x -= 1 or x--.

And you need to increment y and decrement x inside the loop, not at the end.

function playLoop() {
  var x = parseInt(document.getElementById("amount").value);
  var y = 0;
  while (x > 0) {
    var die1 = Math.floor((Math.random() * 6) + 1);
    var die2 = Math.floor((Math.random() * 6) + 1);
    if (die1 + die2 == 7) {
      x += 4;
    } else {
      x--;
    }
    y++;
    x--;
  }

  document.getElementById("result").innerHTML = y;
}
<div class="container">
  <label>Starting Bet:</label>
  <input id="amount" type="text">
  <button onclick="playLoop()">Play</button>
  <span id="result"></span>
</div>