Reputation: 11
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
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:
for
and id
attributes for Label and Input if you wrap your text and input in <label>
on*
attribute handlers! JS should be in one place only and that's the respective tag or file. Use Element.addEventListener() insteadUpvotes: 1