jQuery create table produce only one cube(box) instead of full table - javascript

I'm trying to create a simple table with jQuery.
Currently I got on the browser one single black cube, while the goal is to have table with 5 rows and 5 cols cubes colored black.
Html:
<table class="t"> </table>
CSS:
.box {
width:50px;
height:50px;
background-color:black
}
JS
let $table = $('.t')
let $td = $('<td>').addClass('box')
for (let i = 0; i < 5; i++)
{
let $tr = $('<tr>')
for (let k = 0; k < 5; k++) {
$tr.append($td)
$table.append($tr)
}
$tr.appendTo($table);
}

Related

Javascript set first column style

I'm using javascript to modify a page's styling and it's working great. The next step however is to change the styling of the first column of a table. How can I identify and set the styling of the first column only? My other changes so far are based on ID or based on a number of items having a class. In this example I just know they are TH or TD elements, and I want to change the ones in the first column.
In case anyone asks, this is my code so far... this is working and doesn't include anything to do with setting the style of the first column
function rotate_headers() {
const collection = document.getElementsByTagName("th");
for (let i = 0; i < collection.length; i++)
{
collection[i].innerHTML =
'<div style="padding-left: 100%;"><div style="transform: translate(7px, 3px) rotate(315deg); width: 30px;"><span style="border-bottom: 1px solid #ccc; padding: 5px 10px; color:grey;"' + collection[i].innerHTML + '</span> </div></div>';
// collection[i].style.background = "#6877c3"; //
//collection[i].style.height = "100px"; //
}
const collection2 = document.getElementsByClassName("table-bordered");
for (let i = 0; i < collection2.length; i++)
{ collection2[i].style.border = "0px";
collection2[i].style.marginTop = "95px";
}
const collection3 = document.getElementsByClassName("highlight");
for (let i = 0; i < collection3.length; i++)
{ collection3[i].classList.remove("highlight"); }
const collection4 = document.getElementsByClassName("table-content");
for (let i = 0; i < collection4.length; i++)
{ collection4[i].style.padding = "1rem 1rem"; }
const collection5 = document.getElementsByClassName("table-content");
for (let i = 0; i < collection5.length; i++)
{ collection5[i].style.width = "100px";
collection5[i].style.position = "relative";
collection5[i].style.whiteSpace = "nowrap";
collection5[i].style.overflowX = "scroll";
collection5[i].style.overflowY = "hidden";
}
}
The below code does what I want, but only if my table has an ID... which mine typically do not.
var table = document.getElementById('test');
for (var i = 1; i < table.rows.length; i++) {
var firstCol = table.rows[i].cells[0]; //first column
firstCol.style.background = 'red'; // or anything you want to do with first col
}
The code below does not work... which is my problem
var table = document.getElementsByTagName("table");
for (var i = 1; i < table.rows.length; i++) {
var firstCol = table.rows[i].cells[0]; //first column
firstCol.style.background = 'red'; // or anything you want to do with first col
}
You can just use document.querySelectorAll('tr th:first-child, tr td:first-child') then iterate the result setting the styles you want.
let firstCol = document.querySelectorAll('tr th:first-child, tr td:first-child')
for (let i = 0; i < firstCol.length; i++) {
firstCol[i].style.color = 'red'
}
<table>
<tr>
<th>one</th>
<th>two</th>
<th>three</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
I think you will find answer in next article:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Basics
Styling without
There is one last feature we'll tell you about in this article before we move on. HTML has a method of defining styling information for an entire column of data all in one place — the and elements. These exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every or in the column, or use a complex selector such as :nth-child.

Adding two different buttons on each cells dynamically

Please I am building a dynamic table and I want when j==3; two different buttons(add and reject buttons) should be added. I don't know the best way it will appear in JSON format. And when I looped, I got only one button on the table. Is there a possible way to do this better? I am new to javaScript.
**This is js **
var contributionTable = document.querySelector("#contributionTable");
if(myContribution.contributions.length>0){
var col = [];
for (var i = 0; i < myContribution.contributions.length; i++) {
for (var key in myContribution.contributions[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE HEAD .
var tHead = document.querySelector("#tableHead");
var hRow = document.querySelector("#tableRow");
tHead.appendChild(hRow);
contributionTable.appendChild(tHead);
var tBody = document.createElement("tbody");
for (var i = 0; i < myContribution.contributions.length; i++) {
var bRow = document.createElement("tr");
var td = document.createElement("td");
td.innerHTML = i+1;
bRow.appendChild(td);
for (var j = 0; j < 4; j++) {
var td = document.createElement("td");
if (j==3) {
for (let i = 0; i < myContribution.contributions.length; i++) {
let modify = myContribution.contributions[i].modify;
for(let j = 0; j < modify.length; j++){
if (td.textContent==="Accept") {
td.innerHTML='<div class="badge badge-success">'+modify[j]+'</div>';
bRow.appendChild(td);
}else
td.innerHTML='<div class="badge badge-danger">'+modify[j]+'</div>';
bRow.appendChild(td);
}
}
}else{
td.innerHTML = myContribution.contributions[i][col[j]];
bRow.appendChild(td);
}
}
tBody.appendChild(bRow)
}
contributionTable.appendChild(tBody);
}
with the above, I got only the reject button but I want both the add and reject buttons to appear on the same cell in each row.
This is my JSON data
var myContribution = {"contributions":
[
{
"txnNo":"00031",
"name": "Onyinye Okeke",
"Delete":"Delete",
"modify":["Accept","Reject"],
"date":"2020-01-19",
"amount":"100000",
"desc": "Weekly"
},
{
"txnNo":"00031",
"name": "Thompson Philip",
"Delete":"Delete",
"modify":["Accept","Reject"],
"date":"2019-11-09",
"amount":"70000",
"desc": "Daily"
}]}
Perhaps something like this?
var cellContent = '';
for(let j = 0; j < modify.length; j++) {
if (td.textContent==="Accept")
cellContent +='<div class="badge badge-success">'+modify[j]+'</div>';
else
cellContent +='<div class="badge badge-danger">'+modify[j]+'</div>';
}
td.innerHTML = cellContent;
bRow.appendChild(td);
If you want to add styles to the buttons, it is better to update button style using CSS
td > div.badge {
margin: 0 5px; /* no space on top, 5px right space, no bottom space, 5px left space
}

Assign Set Class To HTML Table Created in JavaScript

I'm trying to use JavaScript to create a table based off the amount of rows from one table and amount of columns from another. When doing this, I want to assign the table a couple div id's and a table class in order to have the generated table line up on the right side of my employee table.
My problem is, when I create the table in JavaScript this way, I lose the scroll bars for the x and y axis of the table and it appears below the employee table. Scrolling the table is then done with the window scroll instead of having the table set and scrollable itself. I'm still new to HTML and JavaScript and I can't seem to find where I'm going wrong on my own. Here's my code and a JSFiddle for clarification:
var rows = document.getElementById('dayRow').getElementsByTagName("td").length;
var cols = document.getElementById('employeeCol').getElementsByTagName("tr").length;
var myTable = document.createElement('table');
myTable.classList.add("tableTasks");
var tr1 = null;
var td1 = null;
var text1 = null;
for(let i = 0; i < rows; i++) {
tr1 = document.createElement('tr');
for(let j = 0; j < cols; j++) {
td1 = document.createElement('td');
text1 = document. createTextNode('cell');
td1.appendChild(text1);
tr1.appendChild(td1);
}
myTable.appendChild(tr1);
}
document.body.appendChild(myTable);
.tableTasks {
width:100%;
margin-top:5px;
empty-cells: show;
height:1000px;
line-height: 35px;
width: 100px;
}
#table-wrapper-tasks {
position: relative;
width:81%;
float:right;
}
#table-scroll-tasks {
overflow-x: scroll;
overflow-y: scroll;
max-height: 522px;
}
<div id="table-wrapper-tasks">
<div id="table-scroll-tasks">
</div>
</div>
I'm trying to get something like the image attached.
https://jsfiddle.net/kk05x1cg/#&togetherjs=8kJlzomlvg

chess board using javascript and dom

I'm trying to create a chessboard just like this.
I did create a table And don'r know how to colour it. A also need to print the board name (like A1, A2, ... H8) and be able to pust any figuere in any of the cell.
For start this is the code to create a table:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ChessBoard</title>
<script type="text/javascript">
function CreateTable(){
var poz = document.getElementById('space');
// createing table adn inserting into document
tab = document.createElement('table');
poz.appendChild(tab);
tab.border = '5';
for (var i = 0; i < 8; i++){
// creating row and inserting into document
var row = tab.insertRow(i);
for(var j = 0; j < 8; j++){
// creating cells and fill with data (numbers)
var cell = row.insertCell(j);
cell.innerHTML = i*j;
cell.style.backgroundColor = 'blue';
cell.style.color = 'white';
cell.style.height = '50px';
cell.style.width = '50px';
};
};
}
</script>
</head>
<body onload="CreateTable()" id ="space">
</body>
</html>
How do i fill specific cell with figure (like A3, E5, H8, ...)? Figure are imgages.
Part 2:
I did create a board with your help.
Now I'm trying to do some more from this code.
How do I put several different images into several cells? I'm trying to get right working code, but with no success. This images should appear when the tabel will be loaded (when i press button CreateTable).
I try to create with this code:
In this point I would like to put figures on board. When i create table it should be blank. Then there will be buttons to add figures. At the beginning for each different figure own button
something like this:
function addKing(idStr){
cell = document.getElementById(idStr);
if(cell != null){
// works for color, doesn't work for images!!
// cell.style.backgroundColor = 'red';
cell.src = 'http://akramar.byethost8.com/images/SplProg/DN3/images/50px/king_m.png'
}
}
Button addKing in html:
<button id="king" onclick="addKing(prompt('Insert field'))">Add King</button>
upgrading previousu code to even better if i can put all together and select which one I like to insert (promtpt window 1: what figure:'king, queen, ...', prompt window 2: on what position would you like to insert: 'A1, B3, ...')).
function addImage (type, position){
var img = ??
}
When I pres button add image the prompt window should appear and ask for type (king, queen, root, ...) and location (A1, B4, ...) (for further update perhaps even color (black or white) but let build step by step).
All tis chessboard I would like to build just in javascript and with dom.
link to not working exaple: jsfiddle
Assuming you need to support only modern browsers, the chess-board is entirely do-able with CSS using counters, and generated-content:
table {
empty-cells: show;
}
td {
width: 2em;
height: 2em;
line-height: 2em;
text-align: center;
border: 1px solid #000;
}
tbody tr:nth-child(odd) td:nth-child(even),
tbody tr:nth-child(even) td:nth-child(odd) {
color: #fff;
background-color: #00f;
}
tbody tr:nth-child(even) td:nth-child(even),
tbody tr:nth-child(odd) td:nth-child(odd) {
background-color: #999;
}
tbody {
counter-reset: rowNumber;
}
tr {
counter-increment: rowNumber;
counter-reset: cellNumber;
}
td {
counter-increment: cellNumber;
}
td::before {
content: counter(rowNumber, upper-alpha) counter(cellNumber, decimal);
}
JS Fiddle demo.
The above tested in Chromium 24 and Firefox 19, both on Ubuntu 12.10.
And for a JavaScript approach:
var chess = {
createBoard: function (dimension) {
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
tbody = document.createElement('tbody'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
table.appendChild(tbody);
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
tbody.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
document.body.appendChild(table);
chess.enumerateBoard(table);
}
},
enumerateBoard : function (board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(),
rowCounter,
len,
cells;
for (var r = 0, size = rows.length; r<size; r++){
rowCounter = String.fromCharCode(65 + r);
cells = rows[r].getElementsByTagName('td');
len = cells.length;
rows[r].className = r%2 == 0 ? 'even' : 'odd';
for (var i = 0; i<len; i++){
cells[i].className = i%2 == 0 ? 'even' : 'odd';
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = rowCounter + i;
}
}
}
};
chess.createBoard(10);
JS Fiddle demo.
You can tie an ID to the cell, and then use that ID to reference and updated the background as needed. Here is one example using your code: http://jsfiddle.net/7Z6hJ
function CreateTable(){
var poz = document.getElementById('space');
// createing table adn inserting into document
tab = document.createElement('table');
poz.appendChild(tab);
tab.border = '5';
for (var i = 0; i < 8; i++){
// creating row and inserting into document
var row = tab.insertRow(i);
for(var j = 0; j < 8; j++){
// creating cells and fill with data (numbers)
var cell = row.insertCell(j);
var idStr = String.fromCharCode(97 + i).toUpperCase() + (j+1);
cell.innerHTML = idStr;
cell.id = idStr;
cell.style.backgroundColor = 'blue';
cell.style.color = 'white';
cell.style.height = '50px';
cell.style.width = '50px';
};
};
}
function updateRow(idStr)
{
cell = document.getElementById(idStr);
if(cell != null)
{
cell.style.backgroundColor = 'red';
}
}
As some have mentioned, there is probably a better way to go about this (using css and jQuery, etc) but this answer sticks with what you have so far.
Create a new variable inside the top loop to save the "letter" name of the row (eg. A, B, C).
// creating row and inserting into document
var row = tab.insertRow(i);
var row_letter = String.fromCharCode(65 + i);
Then in the second loop combine the row name and column number.
cell.innerHTML = row_letter + j;
Actually, you need to do some math for correctly coloring and adding labels. Here is the part of code for doing magic:
1 cell.innerHTML = String.fromCharCode(65 + i) + (j + 1);
2 if((i+j)%2){ cell.style.backgroundColor = 'white'; }
3 else{ cell.style.backgroundColor = 'blue'; }
4 cell.style.color = 'black';
5 cell.style.height = '50px';
6 cell.style.width = '50px';
Let me explain. In first line, you take constant 65, which is ASCII code for letter 'A'. While you change the letter by rows, you add i counter to it, so you get 65+0, 65+1, ..., 65+7. Their ASCII equivalents (which you get with String.fromCharCode()) are A, B, ..., H. Now when you have that letter, easily add number of cell to it (j + 1). You can remove '1' and leave just j and make inner loop go from 1 to 8.
Lines 2, 3: Colors are alternating - every second row have the same color. So, just test if is i+j dividable by 2.
For adding figure, you have to make some function that will do cell.innerHTML = <SOME IMAGE>. But, I guess, it's for second question.
Hope I helped you understand the logic.
I case if someone is looking for a way to visualize a chessboard using JS (as I was doing and accidentally came to this question), here is an excellent JS library to do this.
It can create something like this
and much more in no time just by doing the following:
JavaScript
var ruyLopez = 'r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R';
var board = new ChessBoard('board', ruyLopez);
HTML
<div id="board" style="width: 400px"></div>

Combine HTML Table Rows with Javascript

Is there an easy way to combine rows in an HTML table where the first column is the same? I basically have a table set up like:
<table>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
</table>
and I want it to generate:
<table>
<tr><td>test</td><td>37035</td><td>37035</td><tr>
<tr><td>test2</td><td>24690</td><td>24690</td><tr>
</table>
using jQuery:
var map = {};
$('table tr').each(function(){
var $tr = $(this),
cells = $tr.find('td'),
mapTxt = cells.eq(0).text();
if(!map[mapTxt]){
map[mapTxt] = cells;
} else {
for(var i=1, l=cells.length; i<l; i++){
var cell = map[mapTxt].eq(i);
cell.text(parseInt(cell.text()) + parseInt(cells[i].text()));
}
$tr.remove();
}
});
this is a "dumb" script -- no error handling for cases like different number of cells, fields being non-numeric, etc. Add those if necessary.
Also, depending on how it's generated, it's better to do this server-side.
Here's a plain JavaScript version.
window.onload = function() {
var table = document.getElementById('mytable');
var tr = table.getElementsByTagName('tr');
var combined = Array();
for (i = 0; i < tr.length; i++) {
var td = tr[i].getElementsByTagName('td');
var key = td[0].innerText;
if (!combined[key]) {//if not initialised
combined[key] = Array();
for (j = 0; j < td.length - 1; j++) combined[key][j] = 0;
}
for (j = 0; j < td.length - 1; j++)
combined[key][j] += parseInt(td[j + 1].innerText);
}
while (table.hasChildNodes()) table.removeChild(table.lastChild);
var tbody = document.createElement('tbody');//needed for IE
table.appendChild(tbody);
for (var i in combined) {
tr = document.createElement('tr');
tbody.appendChild(tr);
td = document.createElement('td');
td.innerText = i;
tr.appendChild(td);
for (j = 0; j < combined[i].length; j++) {
td = document.createElement('td');
td.innerText = combined[i][j];
tr.appendChild(td);
}
}
}
This will work on tables with any number of rows and any number of cells. I suppose you want to make the sum for every column, that's what this script does.
And as cwolves mentioned, it is more logical to do this serverside. Users that have JS disabled will see the not so clean uncombined table.

Categories