In this lesson we build in JavaScript a simple multiplication table.
To make this example, we will therefore create an html table and in each cell we will insert our elements.
Let’s go back to the example above to understand how to get the elements to be inserted in the cells:
From the figure we can therefore see that if we multiply the rows with the columns we will get the desired results.
In fact, int he firt row we have:
1*1=1; 1*2=2; 1*3=3,…
In the second line we will have instead:
2*1=2; 2*2=4; 2*3=6, ….
And so on for the other lines.
JavaScript multiplication table – development
To create the multiplication table, for example of size 10 x 10, I therefore use two nested for loops with different indices.
Then, in each cell I display the product of the two indices i and j.
Below is the complete JavaScript code that we could insert into our HTML page:
document.write('<table border="1">');
for(let i=1; i <= 10; i++) {
document.write('<tr>')
for(let j=1; j <= 10; j++) {
document.write('<td>' + i * j + '</td>');
}
document.write('</tr>');
}
document.write('</table>');
For simplicity we are using the document.write method to print our multiplication table in JavaScript, but we could also use the methods to manipulate the DOM, having fun creating new elements.
The tutorial for manipulating DOM elements in JavaScript can be found at the following link: DOM in JavaScript.
JavaScript multiplication table - second example
Here is an example of the Pythagorean Table implemented using the createElement() and createTexnode() methods.
Click on the add multiplication table button below, to bring up a 10 x 10 multiplication table.
Multiplication table procedure in JavaScript
The html code that I used to create the example is composed of a button and a div where to display the multiplication table.
The javascript code represents a function that inside it I create a table tag by setting the border attribute to 1.
Then using the two for loops I create the multiplication table where inside each cell I insert, as in the previous example, the product of the two indices.
Using the appendChild method I append all the elements in the html page.
Here is the complete code:
function add() {
var table = document.createElement("table");
table.setAttribute('border', 1)
for (let i=1; i <= 10; i++) {
var row = document.createElement("tr");
for (let j=1; j <= 10; j++) {
var col = document.createElement("td");
var text = document.createTextNode(i * j);
col.appendChild(text);
row.appendChild(col);
}
table.appendChild(row);
}
document.getElementById("table").appendChild(table);
}
Conclusion
In this lesson we have developed the JavaScript multiplication table using various methods.
Some useful links
Introduction to JavaScript language
Learn JavaScript – basic concepts