I am working a project for school in which I am trying to make a simple math game. When the user clicks the start button it will bring display a question and ask for an answer. What I want to to is when the user clicks the start button it will swap the button for to other buttons to move to the next question and one to restart the game. Which works fine, the problem is after the buttons are swapped.
How would I access a sub function from a buttons onclick event? I currently have onclick="return MathGame.resetForm();" but that throws an exception and I can't see where. What is the best way to go about this. Also this is my first attempt at using javascript in this manner so I'm probably going about it the wrong way.
function MathGame(form)
{
var number;
var answer;
var problemArray = new Array(10)
var arrayLength = problemArray.length;
resetGame();
switchButtons();
document.getElementById("question").innerHTML = problemArray[0].questionString;
return false;
function resetGame()
{
for(var i = 0; i < arrayLength; i++)
{
problemArray[i] = new mathProblem();
}
}
function switchButtons()
{
var nextButton = "<input type=\"submit\" value=\"Next\" onclick=\"return MathGame.nextQuestion();\" /> ";
var resetButton = "<input type=\"submit\" value=\"Restart\" onclick=\"return MathGame.resetForm();\" />";
document.getElementById("button").innerHTML = nextButton + resetButton;
}
function nextQuestion()
{
return false;
}
function resetForm()
{
var startButton = "<input type=\"submit\" value=\"Start\" onclick=\"return MathGame();\" />";
document.getElementById("button").innerHTML = startButton;
document.getElementById("question").innerHTML = "Click the Start button to test your math skills";
return false;
}
}
function mathProblem()
{
var randomNumber1 = Math.floor(Math.random() * 20);
var realAnswer = Math.floor(Math.random() * 20);
var randomSwitchArg = Math.floor(Math.random() * 4);
var questionString;
var sum;
var userAnswer;
switch(randomSwitchArg)
{
case 0:
//Addition
this.sum = randomNumber1 + realAnswer;
this.questionString = "Addition: " + randomNumber1 + " + x = " + this.sum + ". What is x?";
break;
case 1:
// subtraction
this.sum = randomNumber1 - realAnswer;
this.questionString = "Subtraction: " + randomNumber1 + " - x = " + this.sum + ". What is x?";
break;
case 2:
//multiplcation
this.sum = randomNumber1 * realAnswer;
this.questionString = "Multiplication: " + randomNumber1 + " * x = " + this.sum + ". What is x?";
break;
case 3:
//division
this.sum = randomNumber1 * realAnswer;
this.questionString = "Division: " + randomNumber1 + " / x = " + this.sum + ". What is x?";
break;
}
}
<form method="post" action="">
<p id="question">
Click the Start buttont to test your math skills.
</p>
<p>
<input type="text" size="4" /> <br />
</p>
<p id="button">
<input type="submit" value="Start" onclick="return MathGame();" />
</p>
</form>
This post has been edited by JeremyC: 11 October 2011 - 09:05 AM

New Topic/Question
Reply



MultiQuote




|