Jeremy Hernandez Jeremy Hernandez - 12 days ago 5
Javascript Question

<input> tag will not work with my function

My HTML

<input>
tag is not working with my Javascript function.

<center>
<input type="text" id=user onsubmit="UserChoice" placeholder="Make your choice...">
</center>


var rock = 1;
var paper = 2;
var scissors = 3;
var spock = 4;
var lizard = 5;

function Game() {

var ComputerChoice = ((Math.Random() * 5) + 1);
var UserChoice = ""

if (UserChoice == ComputerChoice) {
document.getElementById("user").innerHTML = "Its a tie! Your opponent also chose" + ComputerChoice;
}

if (ComputerChoice == 1) {
return "Rock"
}

if (ComputerChoice == 2) {
return "Paper"
}

if (ComputerChoice == 3) {
return "Scissors"
}

if (ComputerChoice == 4) {
return "Spock"
}

if (ComputerChoice == 5) {
return "Lizard"
}

if (ComputerChoice == 1 && UserChoice == 2) {
document.getElementById("user").innerHTML="You won! The computer chose" + ComputerChoice;
}
}

Answer

UserChoice is never assigned a value

You are comparing UserChoice to ComputerChoice, but UserChoice is never assigned a value (other than an empty string). So that comparison is meaningless.

var UserChoice = ""

You need to obtain the user's choice from the DOM.

var UserChoice = document.getElementById('user').value;

onsubmit is not being triggered

You seem to be misunderstanding the onsubmit attribute. It should point to a function to run on form submit. Also, it needs to be in the form tag, not the input tag.

<form onsubmit="Game()">
    <input type="text" id=user onsubmit="UserChoice" placeholder="Make your choice...">
    <input type="submit" value="Submit">
</form>

The center tag is deprecated

Lastly, the <center> tag was deprecated as of HTML 4. To center elements, you can use CSS.

<style>
    center {
        text-align: center;
    }
</style>

<div class="center">
    <input id="user" ...>
</div>
Comments