I am trying to build a multiplication table and display the results, but need to put the x in the top left corner, for some reason it is showing up on the bottom right, what am I doing wrong?
document.write("<table><tbody>");
var blank = "x";
var cols = 0;
var rows = 0;
// ca
for (let rows = 0; rows <= 10; rows++) {
document.write('<tr>');
for (let cols = 0; cols <= 10; cols++)
document.write('<td>' + rows + ',' + cols + '</td>')
}
if (rows === 0 && cols === 0) {
document.write('<td>' + blank + '</td>')
}
"What am I doing wrong?" A lot.
You should think about what you are trying to do first, before going at it.
Your html table is ill-formed, you don't even close the <tr> tags.
for (let row = 0; row <= 10; row++) {
document.write('<tr>');
for (let col = 0; col <= 10; col++) {
if (row == 0 && col == 0) {
document.write('<td>x</td>');
}
else if (row == 0) {
document.write('<td>' + col + '</td>');
}
else if (col == 0) {
document.write('<td>' + row + '</td>');
}
else {
document.write('<td>' + row * col + '</td>');
}
}
document.write('</tr>');
}
Try it here.
Related
I have made this code, but only works for the right half of the diamond, how do I make the full diamond? I need to use nested loops
function myDiamond(){
let row, star;
let toPrint = "";
let rowCount = +prompt("Enter a number to make a diamond");
for (row = 1; row <= rowCount; row++){
for (star = 1; star <= row; star++){
if (star == 1 || star == row){
toPrint +="*";
} else {
toPrint += " ";
}
}
toPrint += "<br>";
}
document.getElementById("figure").innerHTML = toPrint;
for (row = rowCount; row >= 1; row--){
for (star = 1; star <= row; star++){
if (star == 1 || star == row){
toPrint +="*";
} else {
toPrint += " ";
}
toPrint += "<br>";
}
document.getElementById("figure").innerHTML = toPrint;
}
}
Is this what you're trying to do:
function createDimondShape(size) {
var stuff = "";
for (var i = 1; i <= size; i++) {
for (var s = size - 1; s >= i; s--) {
stuff += (" ");
}
for (var j = 1; j <= i; j++) {
stuff += ("* ")
}
stuff += "\n";
}
if (i == size + 1) {
for (var i = 1; i <= size - 1; i++) {
for (var s = 1; s <= i; s++) {
stuff += (" ");
}
for (j = i; j <= size - 1; j++) {
stuff += ("* ");
}
stuff += "\n";
}
}
document.getElementById("figure").innerHTML = stuff;
}
createDimondShape(5);
<pre id="figure"></pre>
Couple of trials here:
function createDimondShape(a, size) {
var stuff = "";
for (var i = 1; i <= size; i++) {
for (var s = size - 1; s >= i; s--) {
stuff += (" ");
}
for (var j = 1; j <= i; j++) {
stuff += ("* ")
}
stuff += "\n";
}
if (i == size + 1) {
for (var i = 1; i <= size - 1; i++) {
for (var s = 1; s <= i; s++) {
stuff += (" ");
}
for (j = i; j <= size - 1; j++) {
stuff += ("* ");
}
stuff += "\n";
}
}
document.getElementById("figure" + a).innerHTML += stuff;
}
createDimondShape(1, 3);
createDimondShape(2, 7);
.f {
display: flex;
flex-direction: row;
}
.f pre {
width: 45%;
}
<div class="f">
<pre id="figure1"></pre>
<pre id="figure2"></pre>
</div>
Preview
With prompt, as asked in the comments:
function createDimondShape(size) {
var stuff = "";
for (var i = 1; i <= size; i++) {
for (var s = size - 1; s >= i; s--) {
stuff += (" ");
}
for (var j = 1; j <= i; j++) {
stuff += ("* ")
}
stuff += "\n";
}
if (i == size + 1) {
for (var i = 1; i <= size - 1; i++) {
for (var s = 1; s <= i; s++) {
stuff += (" ");
}
for (j = i; j <= size - 1; j++) {
stuff += ("* ");
}
stuff += "\n";
}
}
document.getElementById("figure").innerHTML = stuff;
}
createDimondShape(+prompt("Enter a number..."));
<pre id="figure"></pre>
you can do that
document.querySelectorAll('input[type=range]').forEach(r=>r.oninput=_=>r.closest('label').dataset.val=r.value)
btDiamond.onclick=_=>
{
const szD = szDiam.valueAsNumber
oneDiamond.textContent = ''
for(let sp=szD;sp--;)
oneDiamond.textContent += ' '.repeat(sp) + '/'.repeat(szD-sp) + '\\'.repeat(szD-sp) + '\n'
for(let sp=0;sp<szD;sp++)
oneDiamond.textContent += ' '.repeat(sp) + '\\'.repeat(szD-sp) + '/'.repeat(szD-sp) + '\n'
}
label, pre {
margin : 0.5em 1.2em;
}
label input {
vertical-align : middle;
width : 300px;
}
label::after {
display: inline-block;
content : attr(data-val);
width : 2em;
}
<h4>shine bright like a diamond</h4>
<label data-val="6">
size :
<input type="range" id="szDiam" min="1" max="20" value="6">
</label>
<button id="btDiamond"> draw !</button>
<hr>
<pre id="oneDiamond"> your diamond will go here </pre>
The main goal to let player A pick vertical and player B to pick horizontal.
Please run the snippet code to understand my question better!, thanks a lot
I have unique cell with Symbol S and color red, however if i click any cell, it disappears and normal numbers replace it. How i can force the unique Cell to stay and not disappear when I click any cells in my table?
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(c, r) {
showTable(c, r);
isCol = (isCol + 1) % 2;
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (col = 0; col < 7; col++) {
str += "<td onclick='prs(" + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";
}
str += ">";
str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function(){
var tdElements = document.querySelectorAll('#ff td');
tdElements[
RandomGenerator(0, tdElements.length)
].classList.add('uniqueCell');
// update the text of the cell using the class
document.querySelector('.uniqueCell').textContent = 'S';
};
getUnique();
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
.uniqueCell {
background-color: tomato;
text-align: center;
}
<div id="ff"></div>
added
document.querySelectorAll("#ff td")[uniqueCell].innerHTML='S';
document.querySelectorAll("#ff td")[uniqueCell].className ='uniqueCell';
uniqueCell is the random td number
var isCol = 0;
var board = [];
for (r = 0; r < 7; r++) {
var line = [];
for (c = 0; c < 7; c++) {
line.push(RandomGenerator(50, 500));
}
board.push(line);
}
function prs(c, r) {
showTable(c, r);
isCol = (isCol + 1) % 2;
document.querySelectorAll("#ff td")[uniqueCell].innerHTML='S';
document.querySelectorAll("#ff td")[uniqueCell].className ='uniqueCell';
}
function toColor(col, row, chosen_col, chosen_row) {
var ret = false;
switch (isCol) {
case 0:
if (row == chosen_row) {
ret = true;
}
break;
case 1:
if (col == chosen_col) {
ret = true;
}
break;
}
return ret;
}
function showTable(chosen_col, chosen_row) {
var str = "";
str += "<table border=1>";
for (row = 0; row < 7; row++) {
str += "<tr>";
for (col = 0; col < 7; col++) {
str += "<td onclick='prs(" + col + "," + row + ")'";
if (toColor(col, row, chosen_col, chosen_row)) {
str += " class='grn' ";
}
str += ">";
str += board[row][col];
str += "</td>";
}
str += "</tr>";
}
str += "</table>";
document.getElementById("ff").innerHTML = str;
}
function RandomGenerator(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
showTable(-1);
var getUnique = function(){
var tdElements = document.querySelectorAll('#ff td');
uniqueCell=RandomGenerator(0, tdElements.length);
tdElements[
uniqueCell
].classList.add('uniqueCell');
// update the text of the cell using the class
document.querySelector('.uniqueCell').textContent = 'S';
};
var uniqueCell;
getUnique();
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
.uniqueCell {
background-color: tomato;
text-align: center;
}
<div id="ff"></div>
Function showTable(...) generates table every time and replaces with innerHtml with new one. getUnique marks cell only at beginnning.
The possible solution, to store var randomCell = RandomGenerator(...) before showTable(-1), and set class uniqueCell in showTable(...)
I just want to create a multiplication table using Javascript but I don't want each row to have the same result. I will picture that table I want to be created for my work
In this code, the program will print 9 times
for (a = 1; a <= 9; a++) {
document.write('<div style= "float: left; margin: 25px">')
for (i = 1; i <= 9; i++) {
document.write(a + ' x ' + i + ' = ' + a * i + '</br>');
}
}
I already make a table for multiplication but I don't want to make all print 10 times. I want to make different for each table cell
I want to make like this picture and I'm new with JavaScript
var times = 1;
for (a = 9; a > 0; a--) {
for (i = 9; i > 0 && i > (9 - times); i--) {
document.write(a + ' x ' + i + ' = ' + a * i + ' ');
}
document.write('<br>');
times++;
}
You can simply add this to the second loop for (i = 1; i <= a; i++) that way you'll achieve what you want.
for (a = 1; a <= 9; a++) {
document.write('<div style= "float: left; margin: 5px">')
for (i = 1; i <= a; i++) {
document.write(a + ' x ' + i + ' = ' + a * i + '</br>');
}
}
The simple answer is replace this line for (i=1; i<=9; i++) { with this: for (i=a; i<=9; i++) {
for (a = 1; a <= 9; a++) {
document.write('<div style= "float: left; margin: 25px">')
for (i = a; i <= 9; i++) {
document.write(a + ' x ' + i + ' = ' + a * i + '</br>');
}
}
For having the exact same thing as you posted in your picture, this code do the job :
document.write("<table>");
for (a = 9; a > 0; a--) {
document.write("<tr>")
for (i = 9; i > a - 1; i--) {
document.write('<td>' + a + ' x ' + i + ' = ' + a * i + '</td>');
}
document.write('</tr>')
}
document.write("</table>")
Note the use of decrementing loop to match the order of your picture and the usage of the table
What I'm trying to do, is get it so when all of the buttons have been turned to black, it displays the h2 text in the 'lightsoff' div. So if any of the buttons aren't black, the text will be hidden.
I'd like to be able to do it by writing a new function that carries out the checking of the background colour.
function toggle(i, j) {
b = document.getElementById("but_" + i + j)
t = b.innerHTML
if (t == "X") {
b.innerHTML = "O";
b.setAttribute("style", "color:red; background-color:yellow")
}
if (t == "O") {
b.innerHTML = "X";
b.setAttribute("style", "color:white; background-color:black")
}
}
function press(i, j) {
toggle(i, j);
if (i > 0) {
toggle(i - 1, j);
}
if (i < 4) {
toggle(i + 1, j);
}
if (j > 0) {
toggle(i, j - 1);
}
if (j < 4) {
toggle(i, j + 1);
}
}
function generateGrid() {
var d = document.getElementById("button-grid");
var table = document.createElement("table");
d.appendChild(table);
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var cell = document.createElement("td");
cell.innerHTML = "<button type=button id=but_" + i + j +
" onclick=\"press(" + i + ',' + j + ")\"" +
" style=\"color:red; background-color:yellow\"" +
">O</button>";
row.appendChild(cell);
}
table.appendChild(row);
}
toggle(2, 2)
}
window.onload = function() {
generateGrid();
};
<center>
<h1>Lights Off Puzzle</h1>
<h3>Click on the buttons until they all turn black!</h3>
<div id="button-grid"></div>
<div id="lightsoff">
<h2>All the lights are out, you win!</h2>
</div>
</center>
Use classes and count
function toggle(i, j) {
b = document.getElementById("but_" + i + j)
t = b.innerHTML
if (t == "X") {
b.innerHTML = "O";
b.className="on"
}
if (t == "O") {
b.innerHTML = "X";
b.className="off"
}
var off = document.querySelectorAll(".off").length === document.querySelectorAll("#button-grid table tr td").length; // are all off
document.getElementById("lightsoff").style.display= off ? "block":"none"; // ternary shorthand for if (something) x=a; else x=b;
}
function press(i, j) {
toggle(i, j);
if (i > 0) {
toggle(i - 1, j);
}
if (i < 4) {
toggle(i + 1, j);
}
if (j > 0) {
toggle(i, j - 1);
}
if (j < 4) {
toggle(i, j + 1);
}
}
function generateGrid() {
var d = document.getElementById("button-grid");
var table = document.createElement("table");
d.appendChild(table);
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var cell = document.createElement("td");
cell.innerHTML = "<button type=button id=but_" + i + j +
" onclick=\"press(" + i + ',' + j + ")\"" +
" class='red'" +
">O</button>";
row.appendChild(cell);
}
table.appendChild(row);
}
toggle(2, 2)
}
window.onload = function() {
generateGrid();
};
.on {color:red; background-color:yellow}
.off {color:white; background-color:black}
#lightsoff { display: none }
<center>
<h1>Lights Off Puzzle</h1>
<h3>Click on the buttons until they all turn black!</h3>
<div id="button-grid"></div>
<div id="lightsoff">
<h2>All the lights are out, you win!</h2>
</div>
</center>
Toggle a class using classList for the state and then look at the number of elements with that class by using querySelectorAll().
function toggle(i, j) {
b = document.getElementById("but_" + i + j)
b.classList.toggle("on")
b.textContent = b.classList.contains("on") ? "O" : "X"
}
function press(i, j) {
toggle(i, j);
if (i > 0) {
toggle(i - 1, j);
}
if (i < 4) {
toggle(i + 1, j);
}
if (j > 0) {
toggle(i, j - 1);
}
if (j < 4) {
toggle(i, j + 1);
}
console.log("Number of on buttons is: ", document.querySelectorAll("button.on").length)
}
function generateGrid() {
var d = document.getElementById("button-grid");
var table = document.createElement("table");
d.appendChild(table);
for (var i = 0; i < 5; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 5; j++) {
var cell = document.createElement("td");
cell.innerHTML = "<button type=button id=but_" + i + j +
" onclick=\"press(" + i + ',' + j + ")\"" +
" class='on' " +
">O</button>";
row.appendChild(cell);
}
table.appendChild(row);
}
toggle(2, 2)
}
window.onload = function() {
generateGrid();
};
td button{
color: #FFF;
background-color: #000;
}
td button.on {
color: red;
background-color: #FFC;
}
<center>
<h1>Lights Off Puzzle</h1>
<h3>Click on the buttons until they all turn black!</h3>
<div id="button-grid"></div>
<div id="lightsoff">
<h2>All the lights are out, you win!</h2>
</div>
</center>
If you really want to do it without using classes than you need to loop over all the cells and see if any of them are the color. Checking color codes can be a pain because not all browsers return the same thing. I would just check the text.
function check()
var btns = document.querySelectorAll("button")
for (var i=0; i<btns.length; i++) {
if (btns[i].textContent === "O") return false
}
return true
}
I created a dynamic table that contains 20 rows and 2 columns. this is my code:
function createTblBtnClick() {
var tbl = document.createElement("table");
tbl.setAttribute("id", "myTable");
tbl.setAttribute("dir", "rtl");
tbl.cellPadding = 0;
tbl.cellSpacing = 0;
for (i = 0; i < rowNum; i++) {
var row = tbl.insertRow(-1);
for (j = 0; j < colNum; j++) {
var cell = row.insertCell(-1);
cell.setAttribute("id", "cell" + i.toString() + "-" + j.toString());
}
}
document.getElementById("MyTablePanel").innerHTML = "";
document.getElementById("MyTablePanel").appendChild(tbl);
for (i = 0; i < rowNum; i++) {
for (j = 0; j < colNum; j++) {
var srt = "<a href='javascript:select(" + i.toString() + "," + j.toString() + ")' ><div id='div-" + i.toString() + "-" + j.toString() + "'> </div></a>";
document.getElementById("cell" + i.toString() + "-" + j.toString()).innerHTML = srt;
}
}
}
Now I want to add another table in any of my cells. In fact I want to divide each of my cells to 2. How can I do it?
I test below code but it creates 4 column in a row :
function createTblBtnClick() {
var tbl = document.createElement("table");
var tb2 = document.createElement("table");
tbl.setAttribute("id", "myTable");
tbl.setAttribute("dir", "rtl");
tbl.cellPadding = 0;
tbl.cellSpacing = 0;
tb2.setAttribute("id", "myTable1");
//tbl.setAttribute("dir", "rtl");
tb2.cellPadding = 0;
tb2.cellSpacing = 0;
var inner_tb = 0;
for (i = 0; i < rowNum; i++) {
var row = tbl.insertRow(-1);
for (j = 0; j < colNum; j++) {
var cell = row.insertCell(-1);
cell.setAttribute("id", "cell" + i.toString() + "-" + j.toString());
}
}
document.getElementById("MyTablePanel").innerHTML = "";
document.getElementById("MyTablePanel").appendChild(tbl);
////////////////////////////////////////////////////////
var row1 = tb2.insertRow(-1);
for (inner_tb = 0; inner_tb < 2; inner_tb++) {
var cell1 = row.insertCell(-1);
cell.setAttribute("id", "in_cell " + inner_tb.toString());
}
document.getElementById("cell" + i.toString() + "-" + j.toString()).innerHTML = "";
document.getElementById("cell" + i.toString() + "-" + j.toString()).appendChild(tb2);
///////////////////////////////////////////////////////////////
for (i = 0; i < rowNum; i++) {
for (j = 0; j < colNum; j++) {
var srt = "<a href='javascript:select(" + i.toString() + "," + j.toString() + ")' ><div id='div-" + i.toString() + "-" + j.toString() + "'> </div></a>";
document.getElementById("cell" + i.toString() + "-" + j.toString()).innerHTML = srt;
}
}
}
Do exactly the same logic, but append the table to a cell reference.
var innerTbl = document.createElement("table");
//Populate the table...
//With the table populated, append it in the cell of the outertable.
cell.appendChild(innerTbl);
I think this might be what you're trying to do:
http://jsfiddle.net/mPwpq/1/
function createTblBtnClick() {
var rowNum = 20;
var colNum = 2;
var tbl = document.createElement("table");
tbl.setAttribute("id", "myTable");
tbl.setAttribute("dir", "rtl");
tbl.cellPadding = 0;
tbl.cellSpacing = 0;
for (i = 0; i < rowNum; i++) {
var row = tbl.insertRow(-1);
for (j = 0; j < colNum; j++) {
var cell = row.insertCell(-1);
cell.setAttribute("id", "cell" + i.toString() + "-" + j.toString());
// Add inner table with two columns
var innerTbl = document.createElement("table");
innerTbl.innerHTML = '<tr><td>A</td><td>B</td></tr>';
cell.appendChild(innerTbl);
}
}
document.getElementById("MyTablePanel").innerHTML = "";
document.getElementById("MyTablePanel").appendChild(tbl);
}
just a suggestion. Rather than using javascript for doing creating table, why not create the table in the HTML. Get that table in a var using Document.getElementByID. create new string variable like "thisRow" and add the HTML code in the string of the variable like
thisRow += "rowcellinner table"
and then use .append(thisRow);
you can assign the value to thisRow variable in each counter of the loop and append it to table. I find this easier to do.