Multiplication Table in javascript and how about to align the row - javascript

I tried to a do Multiplication Table in JS and I want to print in <p> element out (Use DOM and not use document.write method).
I tried to use " " or "\t" to align column , but when number is double digit (from x3 column) , it got typographic issue.
Does it any ways could solve this problem?
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
for (var j = 1; j <= 9; j++) {
s = s + j + "*" + i + " = " + (i * j) + " ";
}
s = s + "<br>";
}
p1.innerHTML = s;
<pre id="printout"></pre>

Instead of printing table column wise, print row wise.
And wrap your each table in a div, so that aligning them becomes easy.
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
s = s + "<div>";
for (var j = 1; j <= 9; j++) {
s = s + i + "*" + j + " = " + (i*j) + "<Br/>" ;
}
s = s + "</div>";
}
p1.innerHTML = s;
Little bit CSS
#printout {
display:flex;
flex-wrap:wrap;
}
#printout div {
padding:10px;
min-width:100px
}
https://jsfiddle.net/wkg92rud/

Inspiring from #Andreas suggestion, Using <table>
var p1 = document.getElementById("printout");
var s = "";
for (var i = 1; i <= 9; i++) {
let row = document.createElement("tr");
for (var j = 1; j <= 9; j++) {
let col = document.createElement("td");
col.innerText = j + "*" + i + " = " + (i * j);
row.append(col);
}
p1.append(row);
}
td {
padding: 2px 2px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<table id="printout"></table>
</body>
</html>

#Dalvik method is the correct way, styling and alignment should be done through CSS.
However, in other environments like command line, or if you are doing this as an exercise to learn JS you can use string padding, here is an example:
const p1 = document.getElementById("printout");
const LONGEST_ENTRY = 9; // Longest string you will have is 9 characters long
const entries = []
for (let i = 1; i <= 9; i++) {
for (let j = 1; j <= 9; j++) {
const entry = `${j}*${i} = ${(i*j)}`.padEnd(LONGEST_ENTRY, " ") ; // use string interpolation, then pad the string with spaces until the length of LONGEST_ENTRY is reached
entries.push(entry); // store all the entries in an array
}
entries.push("<br/>"); // add a line break at the end of each row
}
p1.innerHTML = entries.join(''); // join all the elements
Here is a jsfiddle as an example

Related

HTML/Javascript multiplication table that takes inputs and highlights the answer on table

As the title states, I need to make a multiplication table using JS and HTML that takes two user inputs and highlights the answer on the table. I have the table made, I'm just struggling with how to take the user inputs from the ids "leftOp" and "rightOp" and highlighting the answer on the table.
var color_td;
document.write("<table border='1px'>");
for(var i = 1; i < 11; i++) {
document.write("<tr style='height:30px;'>");
for(var j = 1; j < 11; j++) {
if(j == 1 || i == 1) {
color_td = "#ccc";
}
else {
color_td = "#fff";
}
document.write("<td style='width:30px;background-color:" + color_td + "'>" + i*j + "</td>");
}
document.write("</tr>");
}
document.write("</table>");
<input type='text' id='leftOp' value=''>
<input type='text' id='rightOp' value=''>
I tried a simple answer with your code style.
Just bind the event "onkeyup" of your inputs to a function that highlight the result cell.
To identify each cell, I add an id and a class to each one. The id is a concatenation of the two indexes and the class difference between border cells and other cells.
To hightlight the rersult cell, you use the inputs values and build the id of the result cell with them.
Don't forget to reset the cells colors on each invocation.
var color_td;
document.write("<table border='1px'>");
for (var i = 1; i < 11; i++) {
var id;
var cellClass;
document.write("<tr style='height:30px;'>");
for (var j = 1; j < 11; j++) {
id = 'cell-' + i + '-' + j;
if (j == 1 || i == 1) {
color_td = "#ccc";
cellClass = "border-cell";
}
else {
color_td = "#fff";
cellClass = "result-cell";
}
document.write("<td class='" + cellClass + "' id='" + id + "' style='width:30px;background-color:" + color_td + "'>" + i * j + "</td>");
}
document.write("</tr>");
}
document.write("</table>");
function inputChange() {
var left = document.getElementById('leftOp').value;
var right = document.getElementById('rightOp').value;
if (!left || !right || left > 10 || left < 1 || right > 10 || left < 1) {
return;
}
var cells = document.getElementsByClassName('result-cell');
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cell.style.backgroundColor = '#fff';
}
var cells = document.getElementsByClassName('border-cell');
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cell.style.backgroundColor = '#ccc';
}
var resultCell = document.getElementById('cell-' + left + '-' + right);
resultCell.style.backgroundColor = '#5fc047';
}
<input type='text' id='leftOp' value='' onkeyup="inputChange()">
<input type='text' id='rightOp' value='' onkeyup="inputChange()">
Important tip: Doesn't use document.write when creating elements and appending new things to DOM, use the correct API for that, such as document.createElement that you can manage the elements much better. In my code below I'm using it to show you as example.
After creating the table, you'll need a function to get the values and the do the verifications and Maths. Also, add the operands i and j (example: "i_j") as the id of each <td> (take care to not have any repeated id), that way you'll have an easy way to found the td you should highlight.
Also, you should have some way to clear the background color of the td which is already highlighted, for that I used an auxiliar function called cleanTds.
Take a look:
var color_td;
let table = document.createElement("table");
document.body.appendChild(table);
for(var i = 1; i < 11; i++) {
let tr = document.createElement("tr");
tr.style.height = "30px"
table.appendChild(tr);
var color_class;
for(var j = 1; j < 11; j++) {
if(j == 1 || i == 1) {
color_class = "grayBg";
}
else {
color_class = "whiteBg";
}
let td = document.createElement("td");
td.className = "tdClass " + color_class;
td.id = i +"_"+ j;
td.style.background = color_td;
td.textContent = i * j;
tr.appendChild(td);
}
}
document.getElementById("calc").onclick = (ev) => {
cleanTds()
let val1 = document.getElementById("leftOp").value;
let val2 = document.getElementById("rightOp").value;
if (val1 == null || val1 == ""){ val1 = 0}
if (val2 == null || val2 == ""){ val2 = 0}
let tdResult = document.getElementById(val1 + "_" + val2)
if (tdResult != null){
tdResult.style.background = "green";
}
}
function cleanTds(){
let tds = document.querySelectorAll("td");
for (var td of tds){
td.style.background = ""
}
}
.tdClass{
height: 30px;
width: 30px;
border: 1px solid;
}
.grayBg{
background: #ccc;
}
.whiteBg{
background: #fff;
}
<input type='text' id='leftOp' value=''>
<input type='text' id='rightOp' value=''>
<button id="calc">Calculate</button>
This should get you started. it's triggered when the enter key is pressed
var color_td;
document.write("<table border='1px'>");
for(var i = 1; i < 11; i++) {
document.write("<tr style='height:30px;'>");
for(var j = 1; j < 11; j++) {
var idName = 'R'+i + 'C' + j;
if(j == 1 || i == 1) {
color_td = "#ccc";
}
else {
color_td = "#fff";
}
document.write("<td id='"+idName + "'style='width:30px;background-color:" + color_td + "'>" + i*j + "</td>");
}
document.write("</tr>");
}
document.write("</table>");
left = document.getElementById("leftOp");
right = document.getElementById("rightOp");
document.getElementById("rightOp")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
left = document.getElementById("leftOp");
right = document.getElementById("rightOp");
var idName = 'R' + leftOp.value + 'C' + rightOp.value;
document.getElementById(idName).style.backgroundColor = "lightblue";
}
});
<input type='text' id='leftOp' value=''>
<input type='text' id='rightOp' value='' >

Creating table or multi-dimensional grid using JavaScript

I'm trying to create a word search puzzle and am beginning by generating a table of random letters. I want to have a table of any number by number, so 10X10 for example, but so far I'm only able to generate a column and can't figure out how to create more columns or the entire grid.
var firstCol = [];
for (var i = 0; i <= 10; i++){
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
var random = parseInt(Math.random()*characters.length);
var letter = characters.charAt(random); //returning random letter
var innerArrays = ['<td>' + letter + '</td>'];
firstCol.push(innerArrays);
};
for (var i = 0; i <= 10; i++){
document.getElementById('wsBox').innerHTML +=
'<tr>'+ firstCol[i] + '</tr>';
};
and this is my HTML...
<table>
<tbody id="wsBox">
</tbody>
</table>
This is a very basic code.
var cols = 10;
var rows = 10;
var html = "";
for(var i =0; i <= rows; i++) {
html += '<tr>';
for(var h=0; h<= cols; h++) {
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
var random = parseInt(Math.random()*characters.length);
var letter = characters.charAt(random); //returning random letter
html += '<td>' + letter + '</td>';
}
html += '</tr>';
}
document.getElementById('wsBox').innerHTML += html;
Here's working code:
http://jsfiddle.net/42dj7jy8/3/
Script
var rows = [];
var colStr = null;
for(var j = 0; j <= 10; j++) {
colStr = "";
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
for (var i = 0; i <= 10; i++){
var random = parseInt(Math.random()*characters.length);
var letter = characters.charAt(random); //returning random letter
var cell = '<td>' + letter + '</td>';
colStr += cell;
};
rows.push('<tr>' + colStr + '</tr>');
}
document.getElementById('wsBox').innerHTML += rows.join("");
Some CSS to wash it down with
td {
border: 1px solid black;
padding: 4px;
text-align: center;
vertical-align: middle;
width: 20px;
height: 20px;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
Here's output
This uses arrays to build the cells and rows of the grid which are joined together with the join method. Simply pass the dimensions of the grid into the function. One loop only.
function createGrid(x, y) {
var rows = [], cells = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
// a complete grid is x * y dimensions
for (var i = 0, l = x * y; i < l; i++) {
letter = characters.charAt(Math.random() * characters.length);
cells.push('<td>' + letter + '</td>');
// when we reach the last column of the row
// push the cells into the row array and reset
// the cells array
if (i !== 0 && (i + 1) % x === 0) {
rows.push('<tr>' + cells.join('') + '</tr>');
cells = [];
}
}
return rows.join('');
}
Grab the element and use insertAdjacentHTML to add the compiled grid HTML.
var tbody = document.getElementById('wsBox');
tbody.insertAdjacentHTML('beforeend', createGrid(10, 10));
DEMO - 10 x 10 grid
DEMO - 3 x 4 grid

Add alphabets dynamically as html row increments

How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";

How to make this table of prime numbers display in reverse

I have created a table that displays all prime numbers from 2-1013 but it is displaying from the bottom right to the top left and I would like it to display from the top left to the bottom right. How would I achieve this?
<!DOCTYPE HTML Public>
<html>
<head>
<title>Prime Numbers</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
</head>
<body onload='CalcPrime()'>
<script type='text/javascript'>
function CalcPrime() {
var setIt = 0;
var count = 0;
var num = 3;
var primeArray = new Array();
primeArray.unshift(2)
while (count < 169) {
setIt = 0;
var i = 2
while (i < num + 1) {
if (num % i == 0) {
setIt = setIt + 1;
}
i = i + 1
}
if (setIt < 2) {
primeArray.unshift(num);
count = count + 1;
}
num = num + 1;
}
var a;
document.write("<table cols='10' border='1'>");
document.write("<tr><th colspan=10 border='1'>Prime Numbers 2-1013</th></tr>");
for (var it = 0; it < 161; it = it + 10) {
document.write("<tr>");
for (var colm = 0; colm < 10; colm++) {
a = it + colm;
document.write("<td style='border:1px line;padding:10px;'>" + primeArray[a] + "</td>");
}
}
}
</script>
</body>
</html>
If you push your values onto the array instead of unshifting them, that will put them at the end of your array instead of the start. Which would do exactly what you want.
This will get you close. Basically, instead if incrementing your indices, decrement them. Instead of starting with 0, start with the final number and go down to zero. In other words, reverse your loop.
for (var it = 161; it >= 0; it -= 10) {
document.write("<tr>");
for (var colm = 10; colm >= 0; colm--) {
a = it + colm;
document.write("<td style='border:1px line;padding:10px;'>" + primeArray[a] + "</td>");
}
}
It's not perfect yet, but this will get you close for now. I'll edit after I tweak it a bit.
Before writing the table, reverse the primeArray variable by adding:
primeArray = primeArray.reverse();

Populating multidimensional array

The code below came as an included file with a beginner puzzle app tutorial I'm working through. The code works, however now that I've completed the tutorial, I'm trying to read through the files that came preloaded which were not explained.
I'm really tripped up over the "spacecount" variable, and what exactly it's doing. Can anyone comment each line in plain english, so that I can better understand how exactly the code below is populating the rowCount array. Thank you so much.
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i]="";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols-1) rowCount[i] += spaceCount + " ";
} else {
if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}
Here's a slightly more legible version:
var totalRows = puzzle.length;
var totalCols = puzzle[0].length;
/* Loop through the rows to create the rowCount array
containing the totals for each row in the puzzle */
var rowCount = [];
for (var i = 0; i < totalRows; i++) {
rowCount[i] = "";
spaceCount = 0;
for (var j = 0; j < totalCols; j++) {
if (puzzle[i][j] == "#") {
spaceCount++;
if (j == totalCols - 1) {
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) {
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}
}
}​
The confusing parts are probably the if blocks in the middle.
if (puzzle[i][j] == "#") { // If a puzzle piece is `#` (a space?)
spaceCount++; // Increment the spaceCount by 1.
if (j == totalCols - 1) { // Only if we are on the last column, add the text
// to the row.
rowCount[i] += spaceCount + " ";
}
} else if (spaceCount > 0) { // If the current piece isn't a `#` but
// spaces have already been counted,
// add them to the row's text and reset `spaceCount`
rowCount[i] += spaceCount + " ";
spaceCount = 0;
}​
From what I can tell, this code counts the number of consecutive pound signs and appends this text to each row.

Categories

Resources