How do I get data from a table? - javascript

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();

Related

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

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.

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 to insert new rows in some position in table

I have page with table.
In tbody I show data via angularjs. In thead I have same row as in tbody, but its empty, and when I filled input field and click somewhere (focus lost), one row adds to my table (thead). And I need to make some flag on filled row, as like - rowAdded = true, because without that I clicking on input of one row and rows adds. And one more problem is that rows adds to the end of table.
it's all works on this script:
var tbody = $('.table-timesheet thead');
tbody.on('blur', ':text', function () {
var tr = $(this).closest('tr'),
notEmpty = $(':text', tr).filter(function () {
return $.trim($(this).val()) != '';
}).length;
if (notEmpty) {
$('.note-input').css('width', '88%').css('float', 'left');
$('.timesheet-delete-button').css('display', 'block');
//tr.clone(true).appendTo(tbody).find(':text').val('');
insRow();
}
});
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('table-body').deleteRow(i);
}
function insRow() {
var table = document.getElementById('table-body');
var newRow = table.rows[1].cloneNode(true);
var len = table.rows.length;
newRow.cells[0].innerHTML = len;
var inp1 = newRow.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = newRow.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
table.appendChild(newRow);
}
There is my example in plunker:
http://plnkr.co/edit/rcnwv0Ru8Hmy7Jrf9b1C?p=preview
Is this what you are looking for
function insRow(ind){
var table = document.getElementById('table-body');
var newRow = table.rows[1].cloneNode(true);
var len = table.rows.length;
newRow.cells[0].innerHTML = ind!==undefined ? ind : len;
if(ind!==undefined)
$(table).find('tr:eq('+ind+')').before(newRow);
else table.appendChild(newRow);
}
insRow(2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table-body">
<tbody>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</tbody>
</table>

Appending tr to table appends a new tbody to html table using javascript

Please check this fiddle: http://jsfiddle.net/tn4euhsn/8/
HTML:
<table id="tab" border=1>
<tr>
<td>A col1</td>
<td>A col2</td>
</tr>
</table>
Javascript:
console.log("Here!");
var table = document.getElementById("tab");
var trnew = document.createElement("tr");
trnew.id = "row" + 2;
var td1 = document.createElement("td");
td1.innerHTML= "r2col1";
var td2 = document.createElement("td");
td2.innerHTML= "r2col2";
trnew.appendChild(td1);
trnew.appendChild(td2);
table.appendChild(trnew);
console.log(table.outerHTML);
I am trying to append a new <tr> to a table. But instead a <tbody><tr></tr></tbody>
gets appended, resulting in 2 <tbody> elements in html table.
So whats wrong here? and how do I do it? (I don't want to use jquery)
Yes it already has a default tbody tag so you have to use it instead of introducing new one.
var table = document.getElementById("tab").getElementsByTagName('tbody')[0];
Also you can simplify it like
var table = document.getElementById("tab").getElementsByTagName('tbody')[0];
var trnew = document.createElement("tr");
trnew.id = "row" + 2;
for (var i=1; i<=2; i++) {
var td = document.createElement("td");
td.innerHTML = "r2col" + i;
trnew.appendChild(td);
}
table.appendChild(trnew);
console.log(table.outerHTML);
Update:
While trying to figure out the reason, I came across HTMLTableElement,
If a table has multiple tbody elements, by default, the new row is
inserted into the last tbody. To insert the row into a specific tbody
Here is an updated version of the above code
var table = document.getElementById("tab");
var index = table.getElementsByTagName("tr").length;
var newRow = table.insertRow(index);
newRow.id = "row" + 2;
for (var i = 0; i < 2; i++) {
var newCell = newRow.insertCell(i);
var newText = document.createTextNode("r2col" + i);
newCell.appendChild(newText);
}
console.log(table);
Fiddle
It seems that the browser will give it a tbody by default, try this:
<table border=1>
<tbody id="tab">
<tr>
<td>A col1</td>
<td>A col2</td>
</tr>
</tbody>
</table>
Append to the tbody not to the table.
Updated Fiddle

Categories

Resources