We’re going to make our input mean something. We want to take what the player answers and assign it to a variable so that it can be meaningful to us. We do that by taking its value.
$submit.on(‘click’, function(){
playerAnswer = $playerAnswer.val().trim();
submit();
})
.val() is the jQuery function that gets the value of what’s in the input box. I add the trim function just from experience. If a user adds a space, it will look like the correct answer to them, but the computer may not think so.
After it takes the value, it runs the submit function, what we want it to do after the user enters a value and then clicks on submit. It checks to see what switch is turned on. Right now in our code, everything stays switched on until the page reloads. We’ll want at least to take away the Math Options once they make their choice so that they can’t keep turning on different switches and have them all on at once. We’ll get to all that tidying up later.
function submit() {
if (addition == 1) { addMath();}
if (playerAnswer == answer) {
chosen = winner;
} else {
chosen = winner – 1;
}
mathCheck();
}
This checks if addition is turned on (and this is where you’ll check for subtraction and multiplication as well). If it is on, it runs the addMath function (or subtraction or multiplication) to find the correct answer.
Then, once it has figured out the correct answer, it comes back and checks the players answer against the correct answer. I used the variables from our comparing code so that this will just fit right in. If the player’s answer is right, then they win. We accomplish that by saying chosen = winner (what we used in our compare code).
I renamed compareCheck as mathCheck. We’ll just use it for everything. Instead of fiddling with the compare code that was already working, I just used the variables within it and applied it to the arithmetic. So, the last thing this function does is call the check function which is where it gives the cards to the winner.
function addMath() {
answer = number1 + number2;
}
You’d make one of these functions for subtraction and multiplication as well. Integers are already taken care of!
You can watch the lesson.