How to edit this table responsive script? - javascript

I'm using this script to automatically adapt tables to Smartphone view.
It works perfectly! But in some pages, I will have more than one table, and the script seems working only with the first table.
Look at my example, resize your browser window: http://elenatest.altervista.org/index.html
Here's JS code put in the body:
<script type="text/javascript">
var headertext = [],
headers = document.querySelectorAll("#MyTable th"),
tablerows = document.querySelectorAll("#MyTable th"),
tablebody = document.querySelector("#MyTable tbody");
for(var i = 0; i < headers.length; i++) {
var current = headers[i];
headertext.push(current.textContent.replace(/\r?\n|\r/,""));
}
for (var i = 0, row; row = tablebody.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col.setAttribute("data-th", headertext[j]);
}
}
</script>
Is there a way to make this script running for all the tables in the page?
EDIT
I changed the ID with a CLASS. Here's JS code:
<script type="text/javascript">
var headertext = [],
headers = document.querySelectorAll(".MyTable th"),
tablerows = document.querySelectorAll(".MyTable th"),
tablebody = document.querySelector(".MyTable tbody");
for(var i = 0; i < headers.length; i++) {
var current = headers[i];
headertext.push(current.textContent.replace(/\r?\n|\r/,""));
}
for (var i = 0, row; row = tablebody.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col.setAttribute("data-th", headertext[j]);
}
}
</script>
And obviously in my HTML:
<table class="MyTable">
<!--etc etc-->
</table>

By selecting "table" first, then apply your function on each:
Array.prototype.slice.call(document.querySelectorAll("table")).forEach(function (table) {
var headertext = [];
var headers = table.querySelectorAll("th");
var tablebody = table.querySelector("tbody");
var i, j, row, col;
for(var i = 0; i < headers.length; i++) {
headertext.push(headers[i].textContent.replace(/\r?\n|\r/,""));
}
for (i = 0; row = tablebody.rows[i]; i++) {
for (j = 0; col = row.cells[j]; j++) {
col.setAttribute("data-th", headertext[j]);
}
}
});

As you are using an id #MyTable you assume that you'll have only one table on your page.
First, you should change this to class to be semantically more correct.
Then, you need to iterate on tablebody as you do with headers.
for(var i = 0; i < tablebody.length; i++) {

Related

Send a grid as json

I'm relatively new to the world of JavaScript. I create a grid in which I can select any cells.
Now I would like to send all cells as binary with a Json document to the backend. For this purpose, an unselected cell should have a 0 and a selected one should have a 1. I orientate myself on Conway's Game of Life. I've been at it for 2 days now and don't know how best to implement it. Does anyone have an idea?
Here is my code to create the grid
var rows = 10;
var cols = 10;
var grid = new Array(rows);
var nextGrid = new Array(rows);
var startButton = document.getElementById('start');
startButton.addEventListener('click', event => {
initialize()
})
function initializeGrids() {
for (var i = 0; i < rows; i++) {
grid[i] = new Array(cols);
nextGrid[i] = new Array(cols);
}
}
function copyAndResetGrid() {
for (var i = 0; i < rows; i++) {
for (var j = 0; j < cols; j++) {
grid[i][j] = nextGrid[i][j];
}
}
}
// Initialize
function initialize() {
createTable();
initializeGrids();
}
// Lay out the board
function createTable() {
var gridContainer = document.getElementById('gridContainer');
if (!gridContainer) {
// Throw error
console.error("Problem: No div for the drid table!");
}
var table = document.createElement("table");
for (var i = 0; i < rows; i++) {
var tr = document.createElement("tr");
for (var j = 0; j < cols; j++) {
var cell = document.createElement("td");
cell.setAttribute("id", i + "_" + j);
cell.setAttribute("class", "dead");
cell.onclick = cellClickHandler;
tr.appendChild(cell);
}
table.appendChild(tr);
}
gridContainer.appendChild(table);
}
function cellClickHandler() {
var rowcol = this.id.split("_");
var row = rowcol[0];
var col = rowcol[1];
var classes = this.getAttribute("class");
if(classes.indexOf("live") > -1) {
this.setAttribute("class", "dead");
grid[row][col] = 0;
} else {
this.setAttribute("class", "live");
grid[row][col] = 1;
}
}

How do I set an on click event for every cell that calls a function which takes id of cell as a parameter in JavaScript

Here I created a table and assigned each cell an id. What I want to do is something like this cell1.onclik = MyFunction(this.id);
function createTable() {
var table = document.getElementById("tabela2");
for (let j = 0; j < k; j++) {
var row = table.insertRow(0);
for (let i = 0; i < l; i++) {
var cell1 = row.insertCell(0);
cell1.id = "celica" + i + "_" + j;
/*doesnt work: cell1.onclik = MyFunction(this.id); */
}
}
}
Don't use onXXX events. It won't work it there is a content-security-policy on the page.
You just need to listen to the table
function createTable() {
var table = document.getElementById("tabela2");
// document.body.appendChild(table);
for (let j = 0; j < 4; j++) {
var row = table.insertRow(0);
for (let i = 0; i < 4; i++) {
var cell1 = row.insertCell(0);
cell1.textContent = "1";
cell1.id = "celica" + i + "_" + j;
}
}
table.addEventListener("click", function(e) {
console.log(e.target.id);
console.log(e.target.tagName);
});
}
createTable();
<html><body><table id='tabela2'></table></body></html>

How to get all tablecell values from a dynamic table using javascript or jquery

I have dynamic table, it contains 5 textbox controls, i am trying to retrieve label text of all controls. How can i do this.
THanks.
What i had tried:
var table = document.getElementById("ControlTable_");
if (table != null) {
var trlength = table.rows.length;
for (var i = 0; i < trlength; i++) {
var tclenght = table.cells.length;
for (var j = 0; j < tclenght; j++) {
var check = table.rows[i].cells[j].innerText;
}
}
}
Here i am getting innertext undefined
You can have a 2d representation of your table by using something like the following function:
const mapTo = (element, selector, callback) => Array.from(
element.querySelectorAll(selector),
callback
);
const extractText = td => td.textContent;
const tableAsJson = mapTo(
document,
'#ControlTable_ tr',
(row) => mapTo(row, 'td', extractText),
);
console.log('table', tableAsJson);
<table id="ControlTable_">
<tr>
<td>hello</td>
<td>World</td>
</tr>
<table>
if your td elements also contain something like
<label for="something">
Label
</label>
<input />
then something like this may help
const extractText = td => td.querySelector('label').textContent;
Just a note,
please make sure you attach relevant part of your dom structure while asking similar questions in future :)
Here is what I've tried:
var table = document.getElementById("ControlTable_");
if (table != null) {
var trlength = table.rows.length;
for (var i = 0; i < trlength; i++) {
// use this instead of table.cells, because each cell must be specified by a row
// i.e: table.rows[i].cells
var td = table.rows[i].getElementsByTagName('td');
for (var j = 0; j < td.length; j++) {
var check = table.rows[i].cells[j].innerText;
console.log(check);
}
}
}
You need to find and get value from the label in the table cell.
var table_rows = $('#ControlTable_ tr');
for (var i = 0; i < table_rows.length; i++) {
var row = table_rows[i];
var columns = $(row).find('td');
for (var j = 0; j < columns.length; j++) {
var label = $(columns[j]).find('label');
if (label.length > 0) {
var check = label[0].innerText;
console.log(check);
}
}
}
Check below link for working example.
https://jsfiddle.net/rgehlot99/d5zntL6c/2/
(Values can be found in console)

Having trouble trying to style duplicates

I'm checking for duplicates in a table. What I'm trying to accomplish is when I display the first column if it is the same value as the previous row I don't want to display the value. I'm finding the duplicates but I get an error when I try to hide them by using display. style ="none"; My code is below.
I'm Thanking You In Advance
PD
var data=[['e',0,1,2,3,4], ['a',54312,235,5,15,4], ['a',6,7,8,9,232],
['a',54,11235,345,5,6], ['b',0,1,2,3,4], ['b',54312,235,5,15,4],
['c',62,15,754,93,323], ['d',27,11235,425,18,78], ['d',0,1,2,3,4],
['d',54312,235,5,15,4], ['e',6,7,8,9,232], ['e',54,11235,345,5,6],
['e',0,1,2,3,4], ['e',54312,235,5,15,4], ['e',62,15,754,93,323],
['e',27,11235,425,18,78]];
//Create a HTML Table element.
var table = document.createElement("TABLE");
var somedata = document.createElement("TD");
var dvTable = document.getElementById("dvTable");
var elems = document.getElementsByClassName("tableRow");
//Get the count of columns.
var columnCount = data[0].length;
//Add the data rows.
for (var i = 0; i < data.length; i++) {
var row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
//Searching for duplicates
var num = data[i][0];
for (var otherRow = i + 1; otherRow < data.length; otherRow++) {
var dup = data[otherRow][0];
console.log("What is the dup" + dup);
if (num === dup)
{
console.log("duplicate");
dvTable[i].style.display = "none";
}
}
var cell = row.insertCell(-1);
cell.innerHTML = data[i][j];
cell.innerHtml = myZero;
}
}
dvTable is an HTML table element. You can't access the row using dvTable[i].
Try -
dvTable.rows(i).cells(j).style.display = none;

how to add data in a dynamic table

hi i have a table which is created dynamically .this is the code for table creation
function table() {
var body = document.body,
tbl = document.createElement('table'),
tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
tbl.style.width = '100%';
id = 0;
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 3; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode(""));
}
}
$(".lefttablediv").append(tbl);
};
table();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
now it is empty table i want add different data in each tr how can i add data?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<Html>
<body id ="body">
</body>
</html>
<script>
function table() {
var body = document.body;
var tbl = document.createElement('table');
var tableId = document.createAttribute('id');
tableId.value = "table";
tbl.setAttributeNode(tableId);
tbl.style.width = '100%';
alert(tbl);
console.log(tbl);
id=0
for (var i = 0; i < 30; i++) {
var tr = tbl.insertRow();
tr.setAttribute("data-id", i, 0);
for (var j = 0; j < 3; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode("Please add some text here"));
}
}
$("#body").append(tbl);
};
table();
</script>
td.appendChild(document.createTextNode("")); you are appending blank data which showing blank page add some text it will reflect on page
***** td.appendChild(document.createTextNode("Please add sone text here"))****

Categories

Resources