Order dynamically created html table using JavaScript like snakes and ladders game - javascript

I have created a table using javascript and HTML. The table has 50 cells. The cells begin at 50 and end at 1. This is what it looks like now and my code:
I am creating a snakes and ladders game. So 1 needs to begin on the left bottom corner and so on like this:
Is there a way to do this easily or do I need to program each row myself the way I want it?
This is my code so far:
Html:
<html>
<head>
<script>
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'style.css';
document.getElementsByTagName('HEAD')[0].appendChild(link);
</script>
</head>
<html lang="en">
<body>
<div>
<button id="selectbtn" type="button" >Create </button>
<button id="btnMove" type="button" >move to ?</button>
</div>
<div id="myDynamicTable">
</div>
</body>
</html>
Script:
document.getElementById("selectbtn").addEventListener("click", addTable);
function addTable() {
document.getElementById("selectbtn").hidden=true;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
//table.className = "table";
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var n = 50;
var even = true;
for (var i=0; i<5; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<10; j++){
var td = document.createElement('TD');
td.width='75';
td.height = '75';
td.id = n;
if(even){
td.className = "even"
even = false
}
else{
td.className = "odd"
even = true
}
var img = document.createElement('img');
img.id = "img"+n;
td.appendChild(img);
td.appendChild(document.createTextNode(n));
tr.appendChild(td);
n--;
}
}
myTableDiv.appendChild(table);
}
Thank you in advance

Related

Dynamically created html table data not showing in order as expected

function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "31";
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var thead = document.createElement('td');
thead.classList.add("ui-droppable");
thead.appendChild(data[j]);
tre.appendChild(thead);
tbody.appendChild(tre);
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>
I'm trying to order the data that I get from my server to match the columns of my table.
My table columns are days from Monday to Sunday. When my data has more than 7items it needs to separate with another td. The td shows me week 1 and when my data has more than 7 items it needs to separate again that shows week 2 etc.
Update
Im now using a snipped verdion of my code.
Hope someone can help me out with this.
Thank you
There's a few things going on in the code that are problematic.
An attempt to add the table cells to the row, and the row to the table, was made on each iteration of the for loop. That would have produced a lot of rows with single cells had it worked.
It didn't work because there was only ever a single instance of tre, the row variable. So that meant the line tbody.appendChild(tre); did nothing, since appendChild won't append an element that already has a parent element.
Because your data was an array of references to HTMLElements with parents, appending them using appendChild did nothing for the same reason.
I've amended the code below to take care of all of these situations.
Firstly, the code will append a clone of the data to the cell if it's an HTMLElement. I expect in your real code you won't need this, but for this example, why not? It then appends the cell to the row and continues to the next data element.
Secondly, when the data iterator is at 7, before it appends the "Week N" header, it appends a clone of the row, if it has cells on it.
Finally, after appending the clone of the row, the code will reset the row variable to a new instance of a tr element, with no cells.
I also made some variable name and formatting changes to your code just so I could more easily work with it.
function CreateWeakHeader(name) {
var tr = document.createElement('tr');
var td = document.createElement('td');
td.classList.add("cal-usersheader");
td.style.color = "#000";
td.style.backgroundColor = "#7FFF00";
td.style.padding = "0px";
td.appendChild(document.createTextNode(name));
tr.appendChild(td);
var thh = document.createElement('td');
thh.colSpan = "6"; // "31"; Why 31? A week has 7 days...
thh.style.color = "#FFFFFF";
thh.style.backgroundColor = "#7FFF00";
tr.appendChild(thh);
return tr;
}
function htmlTable(data, columns) {
var header = document.createElement("div");
header.classList.add("table-responsive");
var header2 = document.createElement("div");
header2.id = "calplaceholder";
header.appendChild(header2);
var header3 = document.createElement("div");
header3.classList.add("cal-sectionDiv");
header2.appendChild(header3);
if ((!columns) || columns.length == 0) {
columns = Object.keys(data[0]);
}
var tbe = document.createElement('table');
tbe.classList.add("table", "table-striped", "table-bordered");
var thead = document.createElement('thead');
thead.classList.add("cal-thead");
tbe.appendChild(thead);
var tre = document.createElement('tr');
for (var i = 0; i < columns.length; i++) {
var the = document.createElement('th');
the.classList.add("cal-toprow");
the.textContent = columns[i];
tre.appendChild(the);
}
thead.appendChild(tre);
var tbody = document.createElement('tbody');
tbody.classList.add("cal-tbody");
tbe.appendChild(tbody);
var week = 0;
//tbody.appendChild(CreateWeakHeader("Week " + week));
var tre = document.createElement('tr');
for (var j = 0; j < data.length; j++) {
if (j % 7 == 0) {
week++;
/* Major changes start here */
// if the row has cells
if (tre.querySelectorAll('td').length) {
// clone and append to tbody
tbody.appendChild(tre.cloneNode(true));
// reset table row variable
tre = document.createElement('tr');
}
// then append the Week header
tbody.appendChild(CreateWeakHeader("Week " + week));
}
var td = document.createElement('td');
td.classList.add("ui-droppable");
// Set the value of the cell to a clone of the data, if it's an HTMLElement
// Otherwise, make it a text node.
var value = data[j] instanceof HTMLElement ?
data[j].cloneNode(true) :
document.createTextNode(data[j]);
td.appendChild(value);
tre.appendChild(td);
}
// If the number of data elements is not evenly divisible by 7,
// the remainder will be on the row variable, but not appended
// to the tbody, so do that.
if (tre.querySelectorAll('td').length) {
tbody.appendChild(tre.cloneNode(true));
}
header3.appendChild(tbe);
document.body.appendChild(header);
}
$("#tb").click(function() {
var header = document.createElement("div");
header.innerHTML = "test";
var d = [header, header, header, header, header, header, header, header];
htmlTable(d, days);
});
var days = ['Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag', 'Zondag'];
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="tb">CreateTable</button>

JavaScript - Two tables displayed side by side

Newbie coder here. I am creating an app (see below) that has 2 user input fields located side by side. Parse buttons by these user input fields generate 2 separate tables. The tables are placed vertically and I need them to be placed side by side underneath the user input fields. I've seen many solutions to this problem but they all pertain to html code. I don't know how to do that in JS. Please help! An example of user input would be: 1,2,3,4
realArrayRequest = [];
realArrayResponse = [];
function generateTableRequest(){
var body = document.body;
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for(var i=0; i<msg1Req.length; i++){ //rows
var row=document.createElement("tr");
for (var j=0; j < 3; j++){
if (j === 0){ //columns
var cell = document.createElement("td");
var cellText = document.createTextNode(msg1Req[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 1){
var cell = document.createElement("td");
var cellText = document.createTextNode(realArrayRequest[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 2){
var cell = document.createElement("td");
//cell.setAttribute("contenteditable");
var cellText = document.createTextNode(msg1ReqType[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cell = document.createElement("td");
var cellText = document.createTextNode('');
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
}
function generateTableResponse(){
var body = document.body;
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for(var i=0; i<msg1Res.length; i++){ //rows
var row=document.createElement("tr");
for (var j=0; j < 3; j++){
if (j === 0){ //columns
var cell = document.createElement("td");
var cellText = document.createTextNode(msg1Res[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 1){
var cell = document.createElement("td");
var cellText = document.createTextNode(realArrayResponse[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else if (j === 2){
var cell = document.createElement("td");
//cell.setAttribute("contenteditable");
var cellText = document.createTextNode(msg1ResType[i]);
cell.appendChild(cellText);
row.appendChild(cell);
} else {
var cell = document.createElement("td");
var cellText = document.createTextNode('');
cell.appendChild(cellText);
row.appendChild(cell);
}
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
}
function parseUserInputReq(){
realArrayRequest=[];
//cleans the array from all previous values entered before running all functions
var input = document.getElementById("userInputRequest").value;
var noBracketsStr=input.split(",");
//pushing results from noBracketsStr into a new array realArray, because it seems that split() does not change the original array(string)
for(var i = 0; i < noBracketsStr.length; i++){
realArrayRequest.push(noBracketsStr[i])
}
generateTableRequest();
}
function parseUserInputRes(){
realArrayResponse=[];
//cleans the array from all previous values entered before running all functions
var input = document.getElementById("userInputResponse").value;
var noBracketsStr=input.split(",");
//pushing results from noBracketsStr into a new array realArray, because it seems that split() does not change the original array(string)
for(var i = 0; i < noBracketsStr.length; i++){
realArrayResponse.push(noBracketsStr[i])
}
generateTableResponse();
}
//Message elements
//Message 1
const msg1Req = ['Login Command', 'version', 'xID', 'passcode', 'machineID', 'equipment Serial Number', 'userSlot', 'clubID', 'loginType'];
const msg1ReqType = ['integer', 'integer', 'string', 'string', 'string', 'string', 'integer', 'integer', 'string'];
const msg1Res = ['Login Command', 'Version', 'Result', 'User token'];
const msg1ResType = ['integer', 'integer', 'integer', 'string'];
#parseCommandRequest {
width: 50%;
float: left;
};
#parseCommandResponse {
width: 50%;
float: left;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styles.css">
<script defer type="text/javascript" src="index.js" charset="UTF-8"></script>
</head>
<body>
<div id="parseCommandRequest">
<form name="userInputReq">
Request
<input type="text" id="userInputRequest">
<input type="button" value="Parse" onclick="parseUserInputReq()">
</form>
</div>
<div id="parseCommandResponse">
<form name="userInputRes">
Response
<input type="text" id="userInputResponse">
<input type="button" value="Parse" onclick="parseUserInputRes()">
</form>
</div>
</body>
</html>
As you mentioned, there's a lot of different ways to solve this. The most common way to solve problems like this is to use CSS. There's actually a quite easy way to achieve this with the CSS you already have. Instead of injecting the two tables in the body you can inject the tables in #parseCommandRequest and #parseCommandResponse. To do this you simply have to replace body.appendChild(tbl); with code to inject them in the correct divs instead.
This is one possible way to achieve that:
// Replace body.appendChild(tbl); with the following
var parseCommandRequestDiv = document.getElementById("parseCommandRequest");
parseCommandRequestDiv.appendChild(tbl);
// Do the same for the response
var parseCommandResponseDiv = document.getElementById("parseCommandResponse");
parseCommandResponseDiv.appendChild(tbl);

How to check a table is empty or not using javascript

So i have a script like this to make a 2x2 table by javascript
function createtable(){
var tbl = document.getElementById('x');
if (tbl.contains()==false){
tbl.setAttribute('border', '1');
var tbdy = document.createElement('tbody');
for (var i = 0; i < 2; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
var td = document.createElement('td');
tr.appendChild(td);
td.style.height='50px';
td.style.width='50px';
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
}
<form>
<input type="button" value="Create Table" onclick="createtable()"> <br>
</form>
<table id="x"> </table>
I want to check if table x contains anything or not to create itself. Im trying to use the contains() to check but it doesnt work.
You can check the number of rows in the table:
var x = document.getElementById("myTable").rows.length;
See reference here: https://www.w3schools.com/jsref/coll_table_rows.asp
Using this:
var tbl = document.getElementById('x');
if (tbl.rows.length == 0) {
// empty
}
If you want to check if there are any inside table do this
document.getElementById("myTable").rows.length
More info here
you can Check the Row Counts
var tbl = document.getElementById('x');
if(tbl.rows.length==0){
}
if the tbl.rows.length is 0 that means the table don't have any rows
There are multiple ways. One of way, you can use childElementCount property.
if (tbl.childElementCount==0)
{
}
For more details you can refere link
In this case, since there are no child elements or text nodes in your table, you can just check to see if the innerHTML property is falsy. This prevents your createtable function from appending additional children after the function has been run once. For example:
function createtable() {
var tbl = document.getElementById('x');
if (!tbl.innerHTML) {
var tbdy = document.createElement('tbody');
tbl.setAttribute('border', '1');
for (var i = 0; i < 2; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 2; j++) {
var td = document.createElement('td');
tr.appendChild(td);
td.style.height = '50px';
td.style.width = '50px';
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
}
}
<form>
<input type="button" value="Create Table" onclick="createtable()">
<br>
</form>
<table id="x"></table>
Plain javascript:
!![].length
or use Lodash
_.head([]);
// => undefined

How to remove last row in table and set it as first row in javascript?

I have tried following function downward() for removing last row and insert it as first row whereas display() function just creates the table.
<body>
<script>
function downward() {
var table = document.getElementsByTagName('table');
var count = table.rows.length - 1;
var table = table[count];
var rows = table.getElementsByTagName('tr');
var shifted = rows[count];
rows[count].parentNode.removeChild(rows[count]);
table.insertBefore(rows[0]);
}
function display() {
var table = document.createElement('table');
table.setAttribute("id", "tbl");
for (var i = 0; i < 4; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < 4; j++) {
var td = document.createElement('td');
var text = document.createTextNode(j+i);
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
}
</script>
<input id="display" type="button" value="Display" onclick="display();" />
<input id="downward" type="button" value="downward" onclick="downward();" />
</body>
Use .removeChild to remove the last child and insert it before the first element using .insertBefore. See example:
function myFunction(){
var table = document.getElementById("myTable");
var tr = document.getElementById("myTable").lastChild;
table.removeChild[document.getElementsByTagName("tr").lenght];
table.insertBefore(tr, document.getElementById("myTable").firstChild);
}
<table><tbody id="myTable"><tr><td>1</td></tr><tr><td>2</td></tr><tr><td>3</td></tr></tbody></table>
<br>
<button onclick="myFunction()" value="click me to see the result">click me to see the result</button>

Dynamically remove elements with javascript

I got a javascript with a function that creates a table. Now I want the table to be updated/replaced each time I press the button again. I have tried some solutions I have found on the web but none seem to do what I want.
javascript
//Updates table
function myFunction(jsonObject) {
//Build array from the jsonObject
var customers = new Array();
var jsonArr = jsonObject['log'];
for(var i in jsonArr){
customers.push((jsonArr[i]['date']) );
customers.push((jsonArr[i]['time']) );
customers.push((jsonArr[i]['temp']) );
customers.push((jsonArr[i]['humidity']) );
}
//Remove existing tables.-----------------------THIS HAS NO EFFECT!
var myNode = document.getElementById('logDiv');
while (myNode.hasChildNodes()) {
alert("logDiv has nodes, removing them now!")
myNode.removeChild(myNode.firstChild);
}
//----------------------------------------------THIS HAS NO EFFECT!
var container = document.getElementById('logDiv');
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.className = "sortable";
//Adds table headers
var headers = ["Date", "Time", "Temp", "Hum"]
var row1 = document.createElement('tr');
for (var b = 0; b < 4; b++) {
var cell = document.createElement('th');
cell.textContent = headers[b];
row1.appendChild(cell);
counter++;
}
tbody.appendChild(row1);
var counter = 0;
// loop and create rows
for (i = 0; i < customers.length/4; i++) {
var values = customers[i];
var row = document.createElement('tr');
// loop and create columns
for (var b = 0; b < 4; b++) {
var cell = document.createElement('td');
cell.textContent = customers[counter];
row.appendChild(cell);
counter++;
}
tbody.appendChild(row);
}
table.appendChild(tbody);
container.appendChild(table);
}
html/php
<?php
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
$json = json_encode($finalOutput);
?>
<html>
<head>
<script src="script.js" type="text/javascript"></script>
<script src="sorttable.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="UTF-8">
<title>Antgus</title>
</head>
<body>
<button id="btnGenerate" type="button" onclick='myFunction(<?php echo $json ?>)'>Generate log</button>
<br><br>
<div id="logDiv"></div>
</body>
</html>

Categories