Making a maths worksheet with JavaScript
Using a loop is it possible to create a very basic randomly generated maths worksheet. Minimal HTML markup is required as the JavaScript function creates the HTML code when it is called.
The HTML code needed for the maths worksheet
The code below creates a div element and gives it the id 'worksheet'. The JavaScript function will display the generated worksheet inside this div. Also needed is a button used to create a new worksheet when it is pressed.
Place this code between the body tags of your HTML document.
<div id="worksheet"></div>
<input onclick="createWorksheet()" type="button" value="New Sheet?">
The JavaScript code to create the maths worksheet
This function creates the worksheet and displays it in the 'worksheet' div when the 'New Sheet?' button is pressed. Place the following code in the head section of your HTML document.
<script>
function createWorksheet() {
// Change these variables to whatever is required
var totalQuestions = 10;
var difficulty = 100;
// Ensure the worksheet div is empty before creating a new sheet
document.getElementById('worksheet').innerHTML = "";
for (var i = 0; i < totalQuestions; i++) {
// Randomly choose the numbers between zero and the difficulty level
// Truncate these into whole numbers using Math.floor()
var firstNumber = Math.floor(Math.random() * difficulty);
var secondNumber = Math.floor(Math.random() * difficulty);
// Write the sum to the div element using innerHTML
document.getElementById('worksheet').innerHTML += firstNumber + " + " + secondNumber + " = ?<br>";
}
}
</script>
Use the code to generate a maths worksheet
Click 'New Sheet' to create the maths worksheet.
This is a very simple worksheet but it could be improved by using an Array to store the answers to the questions. Another button could then be added to display the answers when pressed.
Different types of questions could also be generated, simple addition questions will quickly become boring!