BlacKuma19
BlacKuma19

Reputation: 11

pick a random input

I'm trying to create a game picker, it's supposed to take the inputs from the form and choose a random game. when I click the button all I get is undefined. thanks for the help

let title = document.querySelectorAll("input");
let values = [];

function chooseGame() {
  for (i = 0; i < values.length; i++); {
    let newValues = values.push(title);
    let randomGame = Math.floor(Math.random() * newValues.length)
    return newValues[randomGame]
  }

}

document.getElementById("gameoptions").innerHTML = chooseGame()
<div id="gameoptions">
  <form>
    <fieldset>
      <div>
        <label for="game1">Game 1:</label>
        <input type="text" id="game1" name="gametitle">
      </div>
      <div>
        <label for="game2">Game 2:</label>
        <input type="text" id="game2" name="gametitle">
      </div>
      <div>
        <label for="game3">Game 3:</label>
        <input type="text" id="game3" name="gametitile">
      </div>
      <div>
        <label for="game4">Game 4: </label>
        <input type="text" id="game4" name="gametitle">
      </div>
      <div id="output"></div>
      <button onclick="chooseGame()" id="answerbutton"> Ready To Play</button>
      <p id="answer"></p>
    </fieldset>
  </form>
</div>

Upvotes: 1

Views: 48

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206344

You're overriding the innerHTML of a form on init... Don't. Simplify your code to just get a random number, you already have your collection of inputs so just pick one using elsTitles[rand] and get the value:

const elsTitles = document.querySelectorAll("#gameoptions input");
const chooseGame = () => {
  const rand = Math.floor(Math.random() * elsTitles.length);
  const randomTitle = elsTitles[rand].value;
  document.querySelector("#answer").textContent = randomTitle;
};

document.querySelector("#answerbutton").addEventListener("click", chooseGame);
#gameoptions label { display: block; }
<div id="gameoptions">
  <label>Game 1: <input type="text" value="Chosen One"></label>
  <label>Game 2: <input type="text" value="Two warriors"></label>
  <label>Game 3: <input type="text" value="Three stars"></label>
  <label>Game 4: <input type="text" value="Win four"></label>
  <button id="answerbutton"> Ready To Play</button>
  <p id="answer"></p>
</div>

Tips:

  • you don't need a HTMLFormElement if you have no plans to submit anything to the backend
  • as you can see you don't need for and id attributes for Label and Input if you wrap your text and input in <label>
  • Don't use inline on* attribute handlers! JS should be in one place only and that's the respective tag or file. Use Element.addEventListener() instead

Upvotes: 1

Related Questions