How to create a dynamic table in a dynamic cell? - javascript

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.

Related

Question regarding JavaScript multiplication table

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.

Check background colour of the grid of buttons in my code

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
}

Make a selectable html table with objects as values

I am been trying to create a html table that is populated by objects.
The table was supposed to be selectable by row (via hover), when the row was hovered over a function ran.
The table headers are in an array:
var topTitles = ["Type","Origin","Destination","T","A","G"];
all the data are sitting inside arrays,
var Type = [];
var Origin = [];
var Destination = [];
var T = [];
var A = [];
var G = [];
I tried to modify an example piece of code, but it was very difficult to conceptualize it and place it into a programatic solution. What is an easy way to map such data directly into a interactive table.
function createTable() {
var table = document.getElementById('matrix');
var tr = addRow(table);
for (var j = 0; j < 6; j++) {
var td = addElement(tr);
td.setAttribute("class", "headers");
td.appendChild(document.createTextNode(topTitles[j]));
}
for (var i = 0; i < origins.length; i++) {
var tr = addRow(table);
var td = addElement(tr);
td.setAttribute("class", "origin");
td.appendChild(document.createTextNode(mode[i]));
for (var j = 0; j < topTitles.length; j++) {
var td = addElement(tr, 'element-' + i + '-' + j);
td.onmouseover = getRouteFunction(i,j);
td.onclick = getRouteFunction(i,j);
}
}
}
function populateTable(rows) {
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < rows[i].elements.length; j++) {
var distance = rows[i].elements[j].distance.text;
var duration = rows[i].elements[j].duration.text;
var td = document.getElementById('element-' + i + '-' + j);
td.innerHTML = origins[i] + "<br/>" + destinations[j];
}
}
}
if (highlightedCell) {
highlightedCell.style.backgroundColor="#ffffff";
}
highlightedCell = document.getElementById('element-' + i + '-' + j);
highlightedCell.style.backgroundColor="#e0ffff";
showValues();
}
This is probably the easiest way I could think of building the table without changing your data structure and make it very clear where all the data is coming from. It is defiantly not the best code, but it should work for your situation.
CodePen
var topTitles = ["Type","Origin","Destination","T","A","G"];
var Type = ["Type1", "type2", "type3"];
var Origin = ["Origin1", "origin2", "origin3"];
var Destination = ["Destination1", "Destination2", "dest3"];
var T = ["t1", "t2","T3"];
var A = ["steaksauce", "a2", "a3"];
var G = ["G1", "G2", "G3"];
var appendString = [];
for(var i =0; i < topTitles.length; i++){
if(!i){
appendString.push("<tr><td>" + topTitles[i] + "</td>");
}
else if(i === topTitles.length -1){
appendString.push("<td>" + topTitles[i] + "</td></tr>");
}
else{
appendString.push("<td>" + topTitles[i] + "</td>");
}
}
for(var i =0; i < Type.length; i++){
appendString.push("<tr><td>" + Type[i] + "</td><td>" + Origin[i] + "</td><td>" + Destination[i] + "</td><td>" + T[i] + "</td><td>" + A[i] + "</td><td>" + G[i] + "</td></tr>");
}
var table = document.getElementById('table');
table.innerHTML = appendString.join('');

how to use following code recursively for different tables

Query(document).ready(function() {
var trCount = $('.Firsttable tr').length;
for (var i = 4; i <=4; i++) {
var $td = $('.Firsttable tr:eq(2) td:eq(' + i + ')'),
highest = 0,
lowest = 9e99;
for (var j = 1; j < trCount; j++) {
$td = $td.add('.Firsttable tr:eq(' + j + ') td:eq(' + i + ')');
}
$td.each(function(i, el){
var $el = $(el);
if (i > 0) {
var val = parseInt($el.text().replace(/[\$,]/g, ''), 10);
if (val < lowest) {
lowest = val;
$td.removeClass('low');
$el.addClass('low');
}
}
});
}
Assign ID attribute to each of your tables and write a function like this:
<script type="text/javascript">
function testTable(tableId) {
var trCount = $('#'+ tableId +' tr').length;
for (var i = 4; i <=4; i++) {
var $td = $('#'+ tableId +' tr:eq(2) td:eq(' + i + ')'),
highest = 0,
lowest = 9e99;
for (var j = 1; j < trCount; j++) {
$td = $td.add('#'+ tableId +' tr:eq(' + j + ') td:eq(' + i + ')');
}
$td.each(function(i, el){
var $el = $(el);
if (i > 0) {
var val = parseInt($el.text().replace(/[\$,]/g, ''), 10);
if (val < lowest) {
lowest = val;
$td.removeClass('low');
$el.addClass('low');
}
}
});
}
</script>
Now just call this function for every table by passing it's id,
<script type="text/javascript>
Query(document).ready(function() {
testTable('table1');
testTable('table2');
}
</script>
Hope it helps, thanks.

How to print 5 multiplication tables per row and remaining 5 in next row using javascript?

This is my demo.jsp page.for this code i'm getting result in single row but i need to print 5 tables per row,remaining 5 multiplication table in second row,vice-versa.where can i change the code to get expected result.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JavaScript Tables</title>
<script>
function getResult() {
var output;
var tableStart = "<table>";
var tableEnd = "</table>";
var trStart = "<tr>";
var trEnd = "</tr>";
var tdStart = "<td>";
var tdEnd = "</td>";
var firstValue = document.getElementById("first").value;
//alert(firstValue);
var secondValue = document.getElementById("second").value;
//alert(secondValue);
if (firstValue < secondValue) {
//alert(secondValue);
document.write(tableStart);
document.write(trStart);
for (var k = firstValue; k <= secondValue; k++) {
document.write(tdStart);
document.write(tableStart);
document.write(trStart);
document.write(tdStart);
document.write(k + ":table");
document.write(tdEnd);
document.write(trEnd);
for (var i = 1; i <= 10; i++) {
output = k * i;
document.write(trStart);
document.write(tdStart);
document.write(k + "*" + i + "=" + output);
document.write(tdEnd);
document.write(trEnd);
}
document.write(tableEnd);
document.write(tdEnd);
}
document.write(trEnd);
document.write(tableEnd);
document.close();
}
else {
//alert(secondValue);
alert("Ending table should be higher number");
}
}
</script>
</head>
<body>
<%
out.println("<table>");
out.println("<tr><td>Starting Number");
out.println("</td><td>Ending Number</td></tr>");
out.println("<tr><td>");
out.println("<input type='text' id='first'>");
out.println("</td><td>");
out.println("<input type='text' id='second'>");
out.println("</td></tr>");
out.println("<tr><td align='right'>");
out.println("<input type='button' value='Get Tables' onclick='getResult()'");
out.println("</td></tr>");
out.println("</table>");
%>
</body>
</html>
You need to nest your loops one more level. There's a new, outer loop that increments j from start to end in steps of 5. Then the k loop goes from j to the end of the current row or the ending value, whichever comes first.
DEMO
function getResult() {
var output;
var tableStart = "<table>";
var tableEnd = "</table>";
var trStart = "<tr>";
var trEnd = "</tr>";
var tdStart = "<td>";
var tdEnd = "</td>";
var firstValue = parseInt(document.getElementById("first").value, 10);
//alert(firstValue);
var secondValue = parseInt(document.getElementById("second").value, 10);
//alert(secondValue);
if (firstValue < secondValue) {
//alert(secondValue);
document.write(tableStart);
for (var j = firstValue; j <= secondValue; j += 5) {
document.write(trStart);
for (var k = j; k <= Math.min(secondValue, j+4); k++) {
document.write(tdStart);
document.write(tableStart);
document.write(trStart);
document.write(tdStart);
document.write(k + ":table");
document.write(tdEnd);
document.write(trEnd);
for (var i = 1; i <= 10; i++) {
output = k * i;
document.write(trStart);
document.write(tdStart);
document.write(k + "*" + i + "=" + output);
document.write(tdEnd);
document.write(trEnd);
}
document.write(tableEnd);
document.write(tdEnd);
}
document.write(trEnd);
}
document.write(tableEnd);
document.close();
} else {
//alert(secondValue);
alert("Ending table should be higher number");
}
}

Categories