if you are building a table, then this is MUCH easier with “.insertRow” and “.insertCell”
function buildit(number1, number2) {
let tbody = document.querySelector('tbody');
let result = '';
let row = tbody.insertRow();
row.insertCell().textContent = 'X';
for (let y = number1; y <= number2; y++) {
// first Row, add the "X" numbers
if (y === number1) {
for (let x = number1; x <= number2; x++) {
row.insertCell().textContent = x;
}
}
// create new Row
row = tbody.insertRow();
// and add the "Y" number first
row.insertCell().textContent = y;
for (let x = number1; x <= number2; x++) {
row.insertCell().textContent = x * y;
}
}
}
buildit(3, 6);
th,
td {
text-align: right;
}
tbody tr:first-child,
tbody tr td:first-child {
color:red;
}
<table>
<tbody>
</tbody>
</table>
Although the example can handle different dimensions, for the sake of simplicity we are making a 10 x 10 table in this explanation.
- Use 2 for loops — the outer loop makes one row then the inner loop makes 10 cells.
- Note that the loops start at 0 index so the iterations are at 10+1 to compensate.
- Inside of each cell is the product of the current row index and the current cell index.
- If the product of row and cell index is 0 then no cell is made.
- Go back to the outer loop once the row has 10 cells and start the next row.
- Repeat this process until there are 10 rows.
Details are commented in example below
// Reference the <table>
const table = document.querySelector('table');
/**
* Renders a given htmlString to a
* given DOM object.
* @param {object<DOM>} node - The tag
* to render HTML to
* @param {string<HTML>} html - The string
* that will be rendered as HTML
*/
const xHTML = (node, html) => {
node.insertAdjacentHTML('beforeEnd', html);
};
/**
* Renders a table with a given number
* of rows and columns. Each cell's
* contents are a product of row and
* column indexes.
* @param {number} rQty - Number of rows
* @param {number} cQty - Number of columns
*/
const mTable = (rQty, cQty) => {
// Make one <tr>...
for (let r = 0; r < rQty + 1; r++) {
xHTML(table, `<tr></tr>`);
/*
If the product of r and c is 0 ?
make nothing :
otherwise make a <td>(r x c)</td>
*/ // Do this >cQty< times
for (let c = 0; c < cQty + 1; c++) {
let cell = r * c === 0 ? '' : `<td>${r*c}</td>`;
xHTML(table.rows[r], cell);
}
/* Once there is >cQty< cells in
row, go to the outer loop to
make next row and so on */
}
};
mTable(10, 10);
html {
font: 2ch/1 Consolas
}
table {
table-layout: fixed;
border-collapse: collapse;
}
td {
width: 10%;
border: 0.5px solid #000;
text-align: center
}
<table></table>
I am having trouble with coding a calculator that asks the user to enter the starting and ending values. The program must use nested for loops. Including row and column labels.
This is what the final table will look like. I will greatly appreciate a link to a relating video or a hint to solve this problem. For example, the output from 1 to 3 might look like this:
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
The output from 3 to 5 might look like this:
3 4 5
3 9 12 15
4 12 16 20
5 15 20 25
The multipliers should appear on top and to the left of the table.
There is one example that I tried to modify for my task.
var result = 'x ';
for (var i = 0; i < 11; i++) {
for (var j = 0; j < 11; j++) {
if(i == 0 && j > 0){
result += '[' + j + ']';
}
else if(j == 0 && i>0){
result += '[' + i + '] ';
}
else if(i>0 && j>0){
result += (i*j) + ' ';
}
}
result += 'n'
}
console.log(result);
Output:
x [1][2][3][4][5][6][7][8][9][10]
[1] 1 2 3 4 5 6 7 8 9 10
[2] 2 4 6 8 10 12 14 16 18 20
[3] 3 6 9 12 15 18 21 24 27 30
[4] 4 8 12 16 20 24 28 32 36 40
[5] 5 10 15 20 25 30 35 40 45 50
[6] 6 12 18 24 30 36 42 48 54 60
[7] 7 14 21 28 35 42 49 56 63 70
[8] 8 16 24 32 40 48 56 64 72 80
[9] 9 18 27 36 45 54 63 72 81 90
[10] 10 20 30 40 50 60 70 80 90 100
I noticed the multipliers are in brackets and the X appears in the top left corner. Is it achieved by using if statements? In my assignment, there must be an empty cell instead of the X. This is what I came up with:
let result = "x";
for(let row = number1; row <= number2; row++){
result += row + "<tr>";
for( let column = number1; column <= number2; column++){
result += "<td>" + row * column +"</td>";
}
result += "<br>"
result += "</tr>"
}
document.getElementById("output").innerHTML = result;
}
My program generates a testing table with a start value equal to 2 and an end value equal to 5, and looks like this:
x 4 6 8 10
6 9 12 15
8 12 16 20
10 15 20 25
It is clear that some logic in the formula within the code isn’t right.
I am attempting to use a document.getElementById() to output the result table. That is one of the requirements. Having some comments explaining the use of table element tags is greatly appreciated.
The program must take start and end values, not just from 1 to 10.
I appreciate everyone’s answers. Some comments within the code that explain what does what and what I am doing wrong are also welcome.
p.s.
I made some corrections to my code. Now it displays ok. One thing is not right. It starts calculation with a number greater than the start number by 1 (eg for input values 2 to 6 it will display 3 to 6). Any ideas?
function displayExpressions(){
let number1 = getNumber();
// console.log(number1)
let number2 = getExpressionsNumber();
// console.log(number2)
if (number1 ==0 || number2 == 0){
document.getElementById("error").innerText = "Enter a number!"
}
else{
let result = " "
for(let row = number1; row <= number2; row++) {
result += "<tr>";
for( let column = number1; column <= number2; column++){
if( row == number1 && column > number1){
result += "<th>" + column + "</th>";
}
else if(column == number1 && row > number1){
result += "<th>" + row + "</th>";
}
else if (row == number1 && column == number1){
result = "<td>" + "x" + "</td>";
}
else{
result += "<td>" + row * column +"</td>";
document.getElementById("output").innerHTML = result;
}
}
result += "</tr>";
}
document.getElementById("output").innerHTML = result;
}
}
I thank everyone who helped. Here is a working example.
'use strict';
window.addEventListener('load', function () {
document.getElementById('number1').addEventListener('focus', inputFocus);
document.getElementById('number2').addEventListener('focus', inputFocus);
document.getElementById('btn').addEventListener('click', main);
document.getElementById('number1').focus();
});
function inputFocus() {
document.activeElement.select();
document.getElementById('error').innerText =
'Enter ' + document.activeElement.id + ' value.';
}
function getNumber() {
let multiplier = document.getElementById('number1').value;
multiplier = Number(multiplier);
return multiplier;
}
function getExpressionsNumber() {
let expressionsNumber = document.getElementById('number2').value;
expressionsNumber = Number(expressionsNumber);
return expressionsNumber;
}
// I have a good feeling that checkInput() does not work at all and is most likely redundant.
function checkInput() {
let number = document.activeElement.value;
console.log(number);
if (isNaN(number) || number.trim().lenght == 0) {
document.getElementById('error').innerText = 'Enter a number!';
return false;
}
return true;
}
function main() {
console.log('Main is called...'); // testing to see if this function is being called.
console.log(checkInput()); // testing if this function returns true...
if (checkInput()) {
document.getElementById('error').innerText = ''; // set the error message to emptry string... good.
displayExpressions(); // call the function to display the output...
}
}
function multiplication(number, expressionsNumber) {
let result = number * expressionsNumber;
return result;
}
function displayExpressions(){
let number1 = getNumber();
// console.log(number1)
let number2 = getExpressionsNumber();
// console.log(number2)
if (number1 <=0 || number2 <= 0){
document.getElementById("error").innerText = "Enter a natural number!"
}
else if(number1 >= number2 ){
document.getElementById("error").innerText = "End value must be grater than Start value!"
}
else{
let result = " "
for(let row = number1; row <= number2 + 1; row++) {
result += "<tr>";
for( let column = number1; column <= number2 + 1; column++){
if( row == number1 && column > number1){
result += "<th>" + (column-1) + "</th>";
}
else if(column == number1 && row > number1){
result += "<th>" + (row - 1) + "</th>";
}
else if (row == number1 && column == number1){
result = "<th>" + "x" + "</th>";
}
else{
result += "<td>" + (row - 1) * (column-1) +"</td>";
document.getElementById("output").innerHTML = result;
}
}
result += "</tr>";
}
document.getElementById("output").innerHTML = result;
}
}
*{
box-sizing: border-box;
}
.fcontainer{
display: flex;
}
div.fcontainer{
justify-content: space-between;
flex-basis: 50%;
margin: 15px;
}
body {
margin: 40px;
background-color: rgb(230, 255, 247);
font-family: 'Roboto', sans-serif;
font-size: calc(10px + (24 - 10) * (100vw - 300px) / (1600 - 300));
}
h1, h2 {
text-align: center;
}
img {
display: block;
width: 300px;
margin: 0 auto;
}
a {
text-decoration: none;
}
p {
margin: 10px 0px;
}
button {
margin: 10px 0px;
}
div.calc {
margin: 0 auto;
display: block;
width: 600px;
background-color: rgb(33, 209, 150);
padding: 20px;
border-radius: 5px;
text-align: center;
}
div.calc p {
text-align: left;
margin-left: 55px;
}
.calc input {
width: 80%;
text-align: right;
border-radius: 3px;
border: none;
}
div.cal h2,
h3 {
text-align: center;
}
#assignment6 div{
margin-top: 10px;
}
div.calc div input,
div.calc div label{
width: 45%;
display: inline-block;
text-align: right;
}
.calc button {
margin-left: 355px;
border-radius: 5px;
border:2px solid #008CBA;
color: black;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
transition-duration: 0.4s;
cursor: pointer;
}
.calc button:hover {
background-color: #008CBA;
color: white;
}
.calc button:active {
transform: scale(0.98);
/* Scaling button to 0.98 to its original size */
box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24);
/* Lowering the shadow */
}
/* Assignment Listings Page start */
#mainPage{
background-image: url(../images/keyboard.jpg);
background-repeat: no-repeat;
background-position: center;
background-size: cover;
height: 350px;
}
#header{
flex-direction: column;
background-color: #9b9ea1;
color: #fff;
max-width: 50%;
margin: 0 auto;
align-self: center;
}
#header h1{
margin: 1em;
}
#main div{
padding: 10px;
background-color: #9b9ea1;
margin: 15px;
width: fit-content;
}
#main a{
padding: 5px;
margin: 5px;
color: #fff;
}
/* Assignment Listings Page end */
/* assignment 3 */
section.fcontainer{
display: flex;
flex-wrap: wrap;
justify-content: space-around;
flex-direction: row;
align-items: stretch;
margin: 0 auto;
max-width: 2600px;
padding: 10px;
border: 1 solid black;
}
section.fcontainer div{
background-color: blanchedalmond;
flex-basis: 45%;
padding: 15px;
margin: 0 15px;
}
/* Assignment Events. Activity 4. Shape area calculator Start*/
body>div{
background-color: gray;
padding: 10px;
color: #fff;
}
div.formulaImage {
flex-basis: 33%;
padding-right: 10px;
}
div.inputForm{
flex-basis: 33%;
display: flex;
flex-direction: column;
justify-content: space-between;
margin-left: 10px;
margin-right: -10px;
}
.inputForm div{
padding-bottom: 5px;
text-align:left;
}
.formulaImage img{
object-fit: cover;
width: 100%;
}
.fcontainer label{
display: inline-block;
width: 50%;
vertical-align: top;
}
.fcontainer input{
display: inline-block;
width: 33%;
text-align: right;
height: 1.2em;
}
.fcontainer output{
display: inline-block;
width: 33%;
text-align: center;
}
#buttonRight{
text-align: end;
margin-right: 80px;
}
#weeklyWageCalculatorButton{
margin-left: 19.5em;
}
/* assignment 5 */
div.formulaImage{
flex-basis: 50%;
}
#assignment5_4{
justify-content: space-evenly;
}
#inputFields div{
padding-top: 5px;
}
@media (max-width: 800px) {
.fcontainer {
flex-direction: column;
}
section.fcontainer div {
flex-basis: 100%;
margin:15px 15px;
width: 100%;
}
div.inputForm{
margin-top: 20px;
}
div.calc {
width: 250px;
}
#weeklyWageCalculatorButton{
margin-left: 0em;
}
#mainPage{
justify-content: center;
}
#header{
max-width: 65%;
}
#btn{
margin: 0;
}
}
#yards{
margin-right: 0;
}
#error{
font-size: smaller;
color: red;
}
/* activity 2, lesson 7 table styles */
table{
border: 1px solid white;
border-collapse: collapse;
}
td{
padding: 10px;
text-align: center;
border: 1px solid white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/styles.css">
<script defer src="./activity2.js"></script>
<style>
table{
border: 1px solid black;
margin: 0 auto;
}
td, th{
width: 50px;
height: 50px;
border: 1px solid black;
}
th{
border: 2px solid black;
}
</style>
</head>
<body>
<div class="calc" id="assignment6">
<h2>Multiplication Table</h2>
<div>
<label for="number1">Start</label>
<input type="number" name="number1" id="number1" min="0" placeholder="0" onchange="">
</div>
<div>
<label for="number2">End</label>
<input type="number" name="number2" id="number2" min="0" placeholder="0" onchange="">
</div>
<p id="error"></p>
<table id="output"></table>
<p><button id="btn">Calculate</button></p>
</div>
</body>
</html>
you code would end up with elements outside of cells in rows … in your first loop, try
if you are building a table, then this is MUCH easier with “.insertRow” and “.insertCell”