I'm prompting the user to enter a number for row and another for column, then construct a table using the given numbers and numbering each cell accordingly.
However, I want my final result to be displayed as a multiplication table, like the image below:
multiplication table image
And here's what my code looks like so far:
var table = document.getElementById("table");
var temp = "<table border = 1 border-collapse = collapse>";
for (var i = 0; i < row; i++){
temp += "<tr>";
if (i == 0){
for (var j = 0; j < column; j++){
temp += "<td height = 20 width = 40>" + (j+1) + "</td>";
}
} else{
for (var j = 0; j < column; j++){
temp += "<td height = 20 width = 40>" + (i+1) + "</td>";
}
}
temp += "</tr>";
}
temp += "</table>";
table.innerHTML=temp;
That is nearly right already. What you are looking for is to put (i+1)*(j+1) in the second for statement.
I'm not sure how you get your user input. Prompt is not usually a great way to get input but because you said that's what you used the example below uses prompt. The problem with it is that it blocks everything else: not only your own webpage, but the entire browser. If you have not done so already, you might consider getting your user-inputted numbers from an HTML form.
You might also want input checking code. I've included it below in a full HTML/JS solution. It gives the user 3 chances to enter a number for both the row and the column. If the user fails to do so, it outputs an error message.
<html>
<head>
</head>
<body>
<div id='table'></div>
<script>
var table = document.getElementById('table');
var attemptCounter = 0;
var maxAttempts = 2;
var temp='<table border = 1 border-collapse = collapse>';
var row;
var column;
while ((typeof row !=='number' || attemptCounter <= maxAttempts) && isNaN(row) ){
var row = parseInt(prompt("Please enter the number of ROWS for your table:"),10);
if(typeof row ==='number' && !isNaN(row)){break;};
attemptCounter++;
}
if(attemptCounter >= maxAttempts+1){
table.innerHTML = 'Error: expected NUMBER for number of rows';
}
if(attemptCounter < maxAttempts+1){
attemptCounter = 0;
while ((typeof column !=='number' || attemptCounter <= maxAttempts) && isNaN(column) ){
var column = parseInt(prompt("Please enter the number of COLUMNS for your table:"),10);
if(typeof column ==='number' && !isNaN(column)){break;};
attemptCounter++;
}
if(attemptCounter < maxAttempts+1){
for (var i = 0; i < row; i++){
temp += "<tr>";
if (i == 0){
for (var j = 0; j < column; j++){
temp += "<td height = 20 width = 40>" + (j+1) + "</td>";
}
} else {
for (var j = 0; j < column; j++){
temp += "<td height = 20 width = 40>" + (i+1)*(j+1) + "</td>";
}
}
temp += "</tr>";
}
temp += "</table>";
table.innerHTML=temp;
} else {
table.innerHTML = 'Error: expected NUMBER for number of columns';
}
}
</script>
</body>
</html>
Your code nearly works. If you change your (i+1) and (j+1) to (i * j) you'll see that the table created works, except for the first row and first column (as multiplying by 0 will always give 0).
However to deal with the multiplication with 0 in the first column and row there needs to be some conditional that checks if one of the values (either i or j are 0) and then changes the value to 1.
I've only changed what happens in your for loop.
for (var i = 0; i < row; i++){
temp += "<tr>";
for (var j = 0; j < column; j++){
// Here I have split your temp string.
temp += "<td height = 20 width = 40>";
if (i == 0 && j ==0){ // if both i and j are 0 then add a 0 to temp.
temp += 0;
} else {
// Multiply them together changing 0 to 1 (solving the 0's problem)
temp += (i == 0 ? 1 : i) * (j == 0 ? 1 : j);
}
temp += "</td>";
}
temp += "</tr>";
}
temp += "</table>";
table.innerHTML=temp;
i==0?1:i is a ternary operator which is just like a little if statement. It checks if i is 0 and if it evaluates to true it returns 1, otherwise it returns the value of i. Read more about it here
Putting it all together,
temp += (i==0?1:i) * (j==0?1:j) multiplies the values in the table together and also prevents multiplication with 0 in the headings.
Build HTML as string is not bad but it is better to work with DOM model. Here is an example.
<!DOCTYPE html>
<html>
<head>
<title>Build Table</title>
<meta charset="utf-8" />
<style type="text/css">
.tbl{border:solid 1px #ccc}
.tbl tr:first-child td,
.tbl td:first-child{background:#ccc;padding:4px}
</style>
<script type="text/javascript">
'use strict';
function buildTable() {
//get numbers from micro-form
var rows = document.getElementById('rows').value;
var cols = document.getElementById('cols').value;
//create table
var tbl = document.createElement('table');
tbl.className = 'tbl';//it is better then inline style
//note that HTML table has its own DOM model
var tr = tbl.insertRow(-1);//insert new row
//first row is special
tr.insertCell(-1).innerHTML = 'X';
//so treat it accordingly
for (var i = 1; i < cols; i++) {
tr.insertCell(-1).innerHTML = i;//insert new cell and set value inside
}
//remaining rows
for (i = 1; i < rows; i++) {
tr = tbl.insertRow(-1);
//first column is special
tr.insertCell(-1).innerHTML = i;
for (var j = 1; j < cols; j++) {
tr.insertCell(-1).innerHTML = i * j;
}
}
//well done. Place our table in a container
document.getElementById('table').appendChild(tbl);
}
</script>
</head>
<body>
<div>
Rows: <input type="number" id="rows" min="2" max="10" value="10" />
Columns: <input type="number" id="cols" min="2" max="10" value="10" />
<button onclick="buildTable()">Build Table</button>
</div>
<div id="table"></div>
</body>
</html>
Related
The order of the numbers in my box is as follows:
function boxNumbers(){
let boxes = document.querySelectorAll('.box')
boxes.forEach((box,i)=>{
if(String(i).length==1 || (String(i).length==2 && Number(String(i)[0]))%2==0){
//box.innerHTML = `${100-i}, i=${i}`
box.innerHTML = 100-i
}
else{
box.innerHTML = String(Number(`${9-Number(String(i)[0])}${String(i)[1]}`)+ 1)
}
})
}
how can I change it to look like this:
You can use this:
function boxNumbers() {
let boxes = document.querySelectorAll('.box');
let n = Math.sqrt(boxes.length);
[...boxes].reverse().forEach((box, i) => {
box.textContent = i % (n * 2) < n ? i + 1 : i + n - 2*(i % n);
})
}
With the assignment to n you make it a bit more generic -- still assuming your table is square. By reversing the iteration, you eliminate the need for the 100- subtraction. What remains is a formula that detects whether we're on a row with a reverse sequence or not, and adapts the number accordingly. The number "1" will always be in the bottom-right corner:
function boxNumbers() {
let boxes = document.querySelectorAll('.box');
let n = Math.sqrt(boxes.length);
[...boxes].reverse().forEach((box, i) => {
box.textContent = i % (n * 2) < n ? i + 1 : i + n - 2*(i % n);
})
}
// Utility to create the table
function fillTable(table, n) {
for (let i = 0; i < n; i++) {
let row = table.insertRow();
for (let j = 0; j < n; j++) {
let cell = row.insertCell();
cell.className = "box";
}
}
}
// Example run with n=5. Adapt as needed
let n = 5
fillTable(document.querySelector('table'), n);
boxNumbers();
table { border-collapse: collapse }
td { border: 1px solid ; width: 20px; height: 20px; text-align: center }
<table></table>
Here is a function which builds a bi-dimensional array and appends it as a table (row/col) to a dom element. You can adapt it to your template as you wish.
Works with any base number, yours is 5
function buildMatrix(baseNumber){
var flip = false;
var countDownNumber = baseNumber * baseNumber;
var currNumber = countDownNumber;
var matrix = "";
for(i = 0; i < baseNumber; i++) {
if(i !== 0){
currNumber = (flip)? countDownNumber + 1 - baseNumber : countDownNumber;
}
matrix += "<tr>";
for(j = 0; j < baseNumber; j++){
matrix += "<td>" + currNumber + "</td>";
// depending on the direction (flip) we increment or decrement
(flip)? currNumber++ : currNumber--;
countDownNumber--;
}
// change direction at the end of a row
flip = !flip;
matrix += "</tr>";
}
return matrix;
}
var baseSquareNumber = 11; // here you put 5
var matrixHtml = buildMatrix(baseSquareNumber);
document.getElementById("matrix").innerHTML = matrixHtml;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<table id="matrix">
</table>
</body>
</html>
So far I have created the code to generate a table that has the number of cells that is defined by the user. In addition to this, the cells which have the prime numbers in it, must be coloured in a different colour. I have also included a function to find the prime numbers, but the approach I took to create the table, doesn't give me an option to implement the function onto the html body.
I would really appreciate any help.
Here's my code..
<html>
<head>
<style>
table{width: 70%;}
</style>
<script>
const numString= window.prompt("What is the loop maximum.? (between 1 and 500)")
let num=parseInt(numString);
if(num<0 || num>500)
{
window.alert("Warning! Must be between 1 and 500. Setting to default
100")
num=100
}
function isPrime(num)
{
for(var i=2; i< num; i++)
if(num % i ===0) return false;
return num>1;
}
</script>
</head>
<body>
<h1>Javascript Loops and Functions</h1><br>
<script>
document.write("<table border=1>");
let rows = num % 10 >= 0 && num % 10 <= 10 ? num / 10 + 1 : num / 10;
let count = 0;
for (row = 1; row <= rows; row++) {
document.write("<tr>");
for (let i = 1; i <= 10; i++) {
if (count >= num+1) break;
document.write("<td>" + count + "</td>");
count++;
}
document.write("</tr>");
}
document.write("</table>");
</script>
</body>
You can use a CSS class to give colors. For instance prime_true could be the class for prime numbers and prime_false for non-primes.
It is not so good practice to use document.write for such a purpose. So I would suggest to have an empty table element in your HTML, and then use loops to populate that table with rows and cells:
function isPrime(num) {
for(var i=2; i< num; i++)
if(num % i ===0) return false;
return num>1;
}
let table = document.querySelector("table");
for (let line = 1; line <= 500; line += 10) {
let row = table.insertRow();
for (let i = line; i < line + 10; i++) {
let td = row.insertCell();
td.textContent = i;
td.className = "prime_" + isPrime(i);
}
}
table { width: 70%; }
td { border: 1px solid; text-align: center }
.prime_true { background: orange }
.prime_false { background: lightgrey }
<h1>Javascript Loops and Functions</h1><br>
<table></table>
NB: this script should be in a script element that is put below the table element.
for (let i = 1; i <= 10; i++) {
if (count >= num+1) break;
if(isPrime(count)){
document.write("<td style='background-color:red'>" + count + "</td>");
} else {
document.write("<td>" + count + "</td>");
}
count++;
}
I am trying to create an X or plus(+) pattern using javascript for-loop but fail to do it.
here is my code
function drawCross(){
var inputVal = document.getElementById("input").value;
if (inputVal % 2 === 0) { // checks if the user's entered value is even
document.getElementById("output").innerHTML = "";
for (var row = 0; row < inputVal; row++) {
for (var col = 0; col < inputVal; col++) {
if (row == col + 3 || row == parseInt(inputVal / 1))
document.getElementById("output").innerHTML += "O";
else
document.getElementById("output").innerHTML += "..";
}
document.getElementById("output").innerHTML += "<br/>";
}
}
}
this is the final result I am trying to achieve
A few issues:
Make sure your output element uses a monospace font. For instance, you could use a pre element for this. Then you don't have to double the points to get something that is still imperfect.
The input number should be odd, not even. Otherwise you don't have a center column/row.
The formula for the second diagonal is not like you have it (division by 1 does not make much sense). Use row == +inputVal - col - 1
Apart from that, also try to interact less with the DOM: only update it when you have the final HTML string.
Here is the code:
function drawCross(){
var inputVal = +document.getElementById("input").value;
var html = "";
if (inputVal % 2 === 1) { // checks if the user's entered value is odd
for (var row = 0; row < inputVal; row++) {
for (var col = 0; col < inputVal; col++) {
if (row == col || row == inputVal - col - 1)
html += "O";
else
html += ".";
}
html += "<br/>";
}
document.getElementById("output").innerHTML = html;
}
}
Enter odd number: <input id="input">
<button onclick="drawCross()">Go</button>
<pre id="output"></pre>
I'm trying to take an HTML table that was created from a Javascript 2D array and I am trying to get sum each row and column in the table excluding the top row and first TD in each row.
var pandlarray = [
[2017-04,0,-118.05,-181.21,-400.43,0]
[2017-05,1510.27,-35.34,-180.99,-351.46,0]
];
// BEGIN - Create HTML table from javascript array.
function makeTableHTML(myArray) {
var result = "<table id='pandltable'>";
result += "<tr><td>Month</td><td>Revenue</td><td>MaterialCost</td><td>Utilities</td><td>Labor</td><td>Margin</td></tr>";
for(var a=0; a<myArray.length; a++) {
result += "<tr>";
for(var j=0; j<myArray[a].length; j++){
if (myArray[a][j] === 0) {
result += "<td>"+0+"</td>";
}
else {
result += "<td>"+myArray[a][j]+"</td>";
}
}
result += "</tr>";
}
result += "<tr><td><strong>Total<strong></td><td></td><td></td><td></td><td></td><td></td></tr></table>";
return result;
}
document.write(makeTableHTML(pandlarray));
// END - Create HTML table from javascript array.
// BEGIN - Total row and columns for pandltable.
$("#pandltable tr:not(:first,:last) td:last-child").text(function(){
var t = 0;
$(this).prevAll().each(function(){
t += t += parseFloat($(this).text(),0) || 0;
});
return t;
});
$("#pandltable tr:last td:not(:first)").text(function(i){
var t = 0;
$(this).parent().prevAll().find("td:nth-child("+(i + 2)+")").each(function(){
t += parseFloat($(this).text(),0) || 0;
});
return t;
});
// END - Total row and columns for pandltable.
Not the most beautiful code I know but this is what I have to work with. The values that are returning right now to the total of each row and column are nowhere near right and they are also showing repeating decimals. Please help.
Made a few changes to your array definition and make table function. Assigned class 'first' to month column to prevent it being added in each row. And used .toFixed() function to limit totals to two decimal points. There is error in first function - calculate total for each row - t += t += -- this might be typo.
var pandlarray = ["2017-04,0,-118.05,-181.21,-400.43,0",
"2017-05,1510.27,-35.34,-180.99,-351.46,0"
];
// BEGIN - Create HTML table from javascript array.
function makeTableHTML(myArray) {
var result = "<table id='pandltable'>";
result += "<tr><td width='20%'>Month</td><td width='20%'>Revenue</td><td width='20%'>MaterialCost</td><td width='20%'>Utilities</td><td width='20%'>Labor</td><td width='20%'>Margin</td></tr>";
for(var a=0; a<myArray.length; a++) {
var thisRow = myArray[a].split(",");
result += "<tr>";
for(var j=0; j<thisRow.length; j++){
if (j === 0) {
result += "<td class='first'>"+thisRow[j]+"</td>";
}
else {
result += "<td>"+thisRow[j]+"</td>";
}
}
result += "</tr>";
}
result +="<tr><td colspan=6> </td> </tr>";
result += "<tr><td><strong>Total<strong></td><td></td><td></td><td></td><td></td><td></td></tr></table>";
return result;
}
document.write(makeTableHTML(pandlarray));
// END - Create HTML table from javascript array.
// BEGIN - Total row and columns for pandltable.
$("#pandltable tr:not(:first,:last) td:last-child").text(function(){
var t = 0;
$(this).prevUntil(".first").each(function(){
t += parseFloat($(this).text(),2) || 0;
});
t = t.toFixed(2);
return t;
});
$("#pandltable tr:last td:not(:first)").text(function(i){
var t = 0;
$(this).parent().prevAll().find("td:nth-child("+(i + 2)+")").each(function(){
t += parseFloat($(this).text(),0) || 0;
});
t = t.toFixed(2);
return t;
});
// END - Total row and columns for pandltable.
I'm trying to get the loop that is in the code after this text to have the information outputted into a table. To explain this further, the function function doEvens() creates a loop that takes uses the number a person enters into the input text box Type in your Number: <input type="number" id="num">, and displays all even numbers between that number and 2 within a paragraph: <p id="space"></p>, when the numbers are displayed within the paragraph they have a semicolon and a space separating them, instead of that I would like the numbers to be within a table, I have tried using createElementById and with no luck, I have tried putting a table between certain areas of the code, with no luck I still have not been able to fix this, I have many other projects I am working on and I am not very good at coding.
<!DOCTYPE html>
<html>
<head>
<script>
function doEvens() {
var number = document.getElementById('num').value;
if(number > 1) {
if(number % 2 == 0) {
while(number > 2) {
document.getElementById("space").innerHTML += (+number - 2) + "; ";
number = +number - 2;
}
} else {
number--;
alert(number);
while(number > 1) {
document.getElementById("space").innerHTML += (+number - 2) + "; ";
number = +number - 2;
}
}
}
}
</script>
</head>
<body>
Type in your Number: <input type="number" id="num">
<button onclick="doEvens();" href="javascript;">Submit</button>
<p id="space"></p>
</p>
</body>
</html>
I have implemented the solution with table. Here it is:
function doEvens() {
var number = document.getElementById('num').value,
table = document.getElementById('evensTable'),
cellsInRow = 20,
evens = [],
tableContent = '',
row = '',
i = 3,
startAt,
numberOfRows;
table.innerHTML = '';
while (i++ < number - 1) {
i % 2 === 0 && evens.push(i);
}
numberOfRows = evens.length / 20;
for (var r = 0; r < numberOfRows; r++) {
row = '<tr>';
startAt = r * cellsInRow;
for (var c = startAt; c < startAt + cellsInRow; c++) {
if (!evens[c]) break;
row += '<td>' + evens[c] + '</td>';
}
row += '</tr>';
tableContent += row;
}
table.innerHTML = tableContent;
}
<body>
Type in your Number:
<input type="number" id="num">
<button onclick="doEvens();" href="javascript;">Submit</button>
<table id="evensTable">
</table>
</body>
This table contains one row, but you can also create more rows in code (say after every 10 numbers print)
If something is not clear for you, please ask me.
UPDATE
I have updated the solution as per your needs.