How can I break row from specific <td> to next row? - javascript

I need to break table headings well as table rows after 4 . Here I'm generating table dynamically from JSON string through jQuery. The table can contain maximum 16 columns, so I need to break it in 4 rows. The output should look like,
<table border=1>
<thead>
<tr>
<th>COLUMN1</th>
<th>COLUMN2</th>
<th>COLUMN3</th>
<th>COLUMN4</th>
</tr>
<tr>
<td>val1</td>
<td>val2</td>
<td>val3</td>
<td>val4</td>
</tr>
</thead>
<tbody>
<tr>
<th>COLUMN5</th>
<th>COLUMN6</th>
<th>COLUMN7</th>
<th>COLUMN8</th>
</tr>
<tr>
<td>val5</td>
<td>val6</td>
<td>val7</td>
<td>val8</td>
</tr>
</tbody>
</table>
I'm using below code to generate HTML Table from JSON,
var txnJson = JSON.parse('<%=jsonObj1%>');
var tableName;
var colspan = 0;
var colHeader = [];
var rowValue = [];
for (var key in txnJson) {
tableName = key;
console.log(key);
for (var secondKey in txnJson[key]) {
console.log(secondKey + ' : ' + txnJson[key][secondKey]);
for (var thirdkey in txnJson[key][secondKey]) {
colHeader.push(thirdkey);
rowValue.push(txnJson[key][secondKey][thirdkey]);
colspan = colspan +1;
console.log(thirdkey + ' : ' + txnJson[key][secondKey][thirdkey]);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < colHeader.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.setAttribute("class", "RptHeader");
th.innerHTML = colHeader[i];
tr.appendChild(th);
}
tr = table.insertRow(-1);
for (var j = 0; j < rowValue.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = rowValue[j];
}
$('#Div<%=i%>').append(table);
I have tried using $('').html($('#Test1 td:gt(4)')).appendTo('#Test1'); but it only breaks single row. I need to iterate it after every four td.
How can I do it?

I'm able to achieve the same using below code,
`var inp = document.createElement("input");
inp.setAttribute("type","hidden");
inp.setAttribute("id","colCnt<%=i%>");
inp.setAttribute("value",colLength);
$(function () {
var colCnt = $("#colCnt<%=i%>").val();
var thLen = 3;
var tdLen = 4;
$('<tr>').html($('#Tab<%=i%> th:gt('+thLen+')')).appendTo('#Tab<%=i%>');
$('<tr>').html($('#Tab<%=i%> td:gt('+tdLen+')')).appendTo('#Tab<%=i%>');
for (var k = 0; k < colCnt; k++) {
thLen = thLen + 4;
tdLen = tdLen + 4;
$('<tr>').html($('#Tab<%=i%> th:gt('+(thLen)+')')).appendTo('#Tab<%=i%>');
$('<tr>').html($('#Tab<%=i%> td:gt('+(tdLen)+')')).appendTo('#Tab<%=i%>');
}
});
Hope, this might help someone.

Related

Loop Through Table and add values in JavaScript

Hello I am trying to loop through a table I have in html and want to add next to the cell depending on the value of the cell. For example the following table I have:
<div>
<h1>My Table</h1>
<table id = "table" class = "searchable sortable">
<tr class = "header">
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<tr>
<td> Up</td>
<td>Down</td>
<td> Up </td>
</tr>
<tr>
<td>Up</td>
<td>Up</td>
<td>Down</td>
</tr>
</table>
<div>
if the value of the cell is equal to up I would like to add a image in the cell of an up arrow,
if down add a image of a down arrow.
You can do it by
var table = document.getElementById('table');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
var image = document.createElement("img");
if(table.rows[r].cells[c].innerHTML === "Up"){
image.src = "/your_image_path_for_up";
} else {
image.src = "/your_image_path_for_down";
}
var newCell = row.insertCell(c+1);
newCell.appendChild(image);
}
}
This will append a new cell with an image to the right of your cell with "Up" or "Down".
Below is the script, which will find all of the cells, loop through them and add appropriate image
<script>
var cells = document.querySelectorAll('td');
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
var cellContent = cell.textContent.toLowerCase().trim();
var img = document.createElement('img')
if (cellContent === 'up') {
img.src = 'src_to_up_arrow_image';
} else if (cellContent === 'down') {
img.src = 'src_to_down_arrow_image';
};
cell.appendChild(img);
}
</script>

How to add headers to the table columns on button click

I am generating a dynamic table with headers based on user input, and adding columns on click of button. While adding columns on click i want to add header to the column as well. If i click on AppendColumns button it should add column with header.
Demo:
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.setAttribute("contenteditable", "true");
table.border = '1';
table.id = 'myTable';
var Header = ["Label", "Control"];
var thead = document.createElement('thead');
table.appendChild(thead);
cellCnt = document.getElementById('txtcols').value;
for (var i = 0; i < cellCnt; i++) {
if (i % 2 == 0) {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[0]));
}
else {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[1]));
}
}
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Click me, Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function AppendColumns() {
var tableCell = document.getElementById('myTable');
for (var i = 0; i < tableCell.rows.length; i++) {
var colCell = tableCell.rows[i].insertCell(tableCell.rows[i].cells.length);
colCell.width = '120';
var insertCell = (colCell, i, 'col');
}
}
<table contenteditable = "true">
<tr>
<td>Row Count</td>
<td>Column Count</td>
<td></td>
</tr>
<tr>
<td><input type="text" id="txtrows" /></td>
<td><input type="text" id="txtcols"/></td>
<td><button onclick="CreateTable()">Create Table</button></td>
<td><button onclick="AppendColumns()">AppendColumn</button></td>
</tr>
</table>
<div id="myDynamicTable"></div>
try this
I think you missed to assign the value for variable cellCnt in the CreateTable() method.
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.setAttribute("contenteditable", "true");
table.border = '1';
table.id = 'myTable';
var Header = ["Label", "Control"];
var thead = document.createElement('thead');
table.appendChild(thead);
thead.id = 'tHead';
cellCnt = document.getElementById('txtcols').value;
for (var i = 0; i < cellCnt; i++) {
if (i % 2 == 0) {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[0]));
}
else {
thead.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[1]));
}
}
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Click me, Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
var Header = ["Label", "Control"];
function AppendColumns() {
var tableCell = document.getElementById('myTable');
var lastIndex = tableCell.rows[0].cells.length-1;
var theader = document.getElementById('tHead');
if(lastIndex % 2 ==1){
theader.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[0]));
}else{ theader.appendChild(document.createElement("th")).
appendChild(document.createTextNode(Header[1]));
}
for (var i = 0; i < tableCell.rows.length; i++) {
var colCell = tableCell.rows[i].insertCell(tableCell.rows[i].cells.length);
colCell.width = '120';
var insertCell = (colCell, i, 'col');
}
}
<table contenteditable = "true">
<tr>
<td>Row Count</td>
<td>Column Count</td>
<td></td>
</tr>
<tr>
<td><input type="text" id="txtrows" /></td>
<td><input type="text" id="txtcols"/></td>
<td><button onclick="CreateTable()">Create Table</button></td>
<td><button onclick="AppendColumns()">AppendColumn</button></td>
</tr>
</table>
<div id="myDynamicTable"></div>

How can I adapt this code to make the rows selectable?

How can I adapt this code to make the rows which have been created by the function selectable. I will then use this in as a part of a form to manipulate the data in the specified row.
function staffData() {
if (firstTimeS) {
firstTimeS = false;
// Select the Table
var tbl = document.getElementById('staffInnerTable');
var th = document.getElementById('tableHead_S');
var headerText = ["ID", "Staff Name", "Role"];
// Set number of rows
var rows = 10;
// Set number of columns
var columns = headerText.length;
// create table header
for (var h = 0; h < columns; h++) {
var td = document.createElement("td");
td.innerText = headerText[h];
th.appendChild(td);
}
// create table data
for (var r = 0; r < rows; r++) {
var cellText = ["UNDEFINED", "UNDEFINED", "UNDEFINED"];
// generate ID
x = getRandomNumber(1000, 1);
cellText[0] = x;
// generate Status
x = generateName();
cellText[1] = x;
// generate Role
x = getRole();
cellText[2] = x;
var tr = document.getElementById("s_row" + r);
for (var c = 0; c < columns; c++)
{
var td = document.createElement("td");
td.innerText = cellText[c];
tr.appendChild(td);
}
}
}
}
EDIT - HTML. Tr already defined in html. Would it be possible to somehow put an onclick on the table rows?
<table style="width: 100%; color:white;" id="staffInnerTable">
<tr id="tableHead_S">
</tr>
<tr id="s_row0"></tr>
<tr id="s_row1"></tr>
<tr id="s_row2"></tr>
<tr id="s_row3"></tr>
<tr id="s_row4"></tr>
<tr id="s_row5"></tr>
<tr id="s_row6"></tr>
<tr id="s_row7"></tr>
<tr id="s_row8"></tr>
<tr id="s_row9"></tr>
</table>
If you do this:
var tr = document.getElementById("s_row" + r);
tr.onclick = function(event) {
alert('Clicked: ' + event.target.parentNode.id)
}
...you'll see that a click is detected that tells you which row was clicked on. Hopefully that's enough to get you started on whatever you wanted to do.

find the <td> column value of respective cell using any javascript library

<table border="1">
<tr>
<td rowspan="3">0</td>
<td>1</td>
<td rowspan="3">2</td>
<td>3</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>X</td>
<td>Y</td>
</tr>
</table>
I want to find the column number of td containing X using jQuery or some other JavaScript library.
For example column number of td containing A is 1 and B is 3.
Also we know that column number of td containing X is 1. But how can we get that pragmatically.
My case here is I need to merge data of all the rows with first row. So while moving through each td I need to know from which column does it belong so that I can merge it to the td of first row of that column.
Please help me if there is any other approach to solve my problem.
Here is the Fiddle.
It gets the index and looks for rowspans and calculates the visible index.
function getColumnNumber(text) {
var $table = $("table").eq(0);
$("td:contains(" + text + ")").css("color", "red");
var $td = $("td:contains(" + text + ")"),
$tr = $td.parent(),
tdPosition = $td.index(),
trPosition = $tr.index(),
position = parseInt(tdPosition);
for (i = 0; i < trPosition; i++) {
for (j = 0; j <= tdPosition; j++) {
var rowSpan = parseInt($table.find('tr').eq(i).find('td').eq(j).attr("rowspan"));
if (typeof rowSpan !== "number") {
rowSpan = 0;
}
if (rowSpan > trPosition) {
position++;
tdPosition++;
}
}
}
console.log(text + " pos: " + position);
return position;
};
getColumnNumber('A');
getColumnNumber('B');
getColumnNumber('1');
getColumnNumber('Y');
This approach is basically storing your table data into an array, and intended if you ever want to expand or modify the structure of your table rowspan. (This does not support colspan)
$(function() {
var tableArr = [],
totalRow = $('table tr').length,
totalCol = 0;
$('table tr').each(function() {
var colLength = $(this).children('td').length;
totalCol = colLength > totalCol ? colLength : totalCol;
});
for (var r = 0; r < totalRow; r++) {
var row = [];
for (var c = 0; c < totalCol; c++) {
row.push(null);
}
tableArr.push(row);
}
$('td').each(function() {
var rowspan = $(this).attr('rowspan');
var rowIndex = $(this).parent('tr').index();
var colIndex = $(this).index();
var text = $(this).html();
if (rowspan && rowspan > 0) {
for (var i = 0; i < rowspan; i++) {
tableArr[i][colIndex] = text;
}
} else {
var lastNull = tableArr[rowIndex].indexOf(null);
tableArr[rowIndex][lastNull] = text;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<td rowspan="3">0</td>
<td>1</td>
<td rowspan="3">2</td>
<td>3</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>X</td>
<td>Y</td>
</tr>
</table>
Your table information is stored within tableArr, which you use to query if you want to get desired columnIndex based on the content of your td.
Usage
// This returns an array containing [row, column];
function getPositionByText(str) {
for (var r = 0; r < tableArr.length; r++) {
for (var c = 0; c < tableArr[r].length; c++) {
if (tableArr[r][c] === str) {
return [r, c]
}
}
}
return null;
}
var position = getPositionByText('X');
var xRow = position[0];
var xCol = position[1];

How do I get data from a table?

How do I pull data (string) from a column called "Limit" in a table ("displayTable") in Javascript?
var table = document.getElementById('displayTable');
var rowCount = table.rows.length;
for (var i = 1; i < rowCount - 1; i++) {
var row = table.rows[i]["Limit"].ToString();
alert(row);
...
}
This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row.
This should give you an idea
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
/* get your cell info here */
/* var cellVal = oCells.item(j).innerHTML; */
}
}
UPDATED SCRIPT
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
// get your cell info here
var cellVal = oCells.item(j).innerHTML;
console.log(cellVal);
}
}
<table id="myTable">
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
</table>
In this code data is a two dimensional array of table data
let oTable = document.getElementById('myTable');
let data = [...oTable.rows].map(t => [...t.children].map(u => u.innerText))
console.log(data);
<table id="myTable">
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
</table>
use Json & jQuery. It's way easier than oldschool javascript
function savedata1() {
var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
td_1: $row.find(':nth-child(1)').text(),
td_2: $row.find(':nth-child(2)').text(),
td_3: $row.find(':nth-child(3)').text()
};
}).get();

Categories

Resources