1

let score = 0;
var myArray = [1, 2, 3, 4, 5];

let randomNumber;

function GuessNumber() {

  var userGuess = document.getElementById("userInput").value;

  var i;
  for (i = 0; i < 1; i++) {
    var randomNumber = myArray[Math.floor(Math.random() * myArray.length)];
  }

  var userGuess = document.getElementById("userInput").value;

  if (userGuess == randomNumber) {
    alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT");
    score++;
  } else {
    alert("SORRY, The correct number was " + randomNumber);
    score = score - 1;
  }
  document.getElementById("GameScore").innerHTML = "Score: " + score;
}
<!doctype HTML>
<html>
  <body>
    <p id="GameScore">Score: 0</p>
    <button onclick="GuessNumber()">Start Game!</button>
    <input id="userInput" type="text">
  </body>
</html>

So the whole point is that instead of writing

var userGuess = document.getElementById("userInput").value

I want the user's input to be a parameter for the function.

The problem however is that i'm using a button to start the function so i'm not sure what to do since the users input is with a textbox.

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
jamiebovin
  • 23
  • 3

2 Answers2

0

You mean something like this?

<!doctype HTML>
<html>
  <body>
    <p id="GameScore">Score: 0</p>
    <button onclick="GuessNumber(document.getElementById('userInput').value)">Start Game!</button>
    <input id="userInput" type="text">
  </body>
</html>
let score = 0;
var myArray = [2, 3];

let randomNumber;

function GuessNumber(userGuess) {

  var i;
  for (i = 0; i < 1; i++) {
    var randomNumber = myArray[Math.floor(Math.random() * myArray.length)];
  }

  if (userGuess == randomNumber) {
    alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT");
    score++;
  } else {
    alert("SORRY, The correct number was " + randomNumber);
    score = score - 1;
  }
  document.getElementById("GameScore").innerHTML = "Score: " + score;
}
Jamie Phan
  • 796
  • 1
  • 7
  • 26
0
  1. Just pass the value of the input to the function.
  2. Consider using addEventListener instead of inline event handlers.

let score = 0;
var myArray = [1, 2, 3, 4, 5];

function GuessNumber(userGuess) {
  var i;
  for (i = 0; i < 1; i++) {
    var randomNumber = myArray[Math.floor(Math.random() * myArray.length)];
  }
  if (userGuess == randomNumber) {
    alert("CONGRATULATIONS!!! YOU GUESSED IT RIGHT");
    score++;
  } else {
    alert("SORRY, The correct number was " + randomNumber);
    score = score - 1;
  }
  document.getElementById("GameScore").innerHTML = "Score: " + score;
}
document.querySelector('button').addEventListener('click', e=>{
  GuessNumber(document.getElementById("userInput").value);
});
<!doctype HTML>
<html>
  <body>
    <p id="GameScore">Score: 0</p>
    <button>Start Game!</button>
    <input id="userInput" type="text">
  </body>
</html>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80