Getting value from table cell in JavaScript...not jQuery - javascript

I can't believe how long this has taken me but I can't seem to figure out how to extract a cell value from an HTML table as I iterate through the table with JavaScript. I am using the following to iterate:
var refTab=document.getElementById("ddReferences")
var ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
row = refTab.rows[i];
for ( var j = 0; col = row.cells[j]; j++ ) {
alert(col.firstChild.nodeValue);
}
}
What is the correct call I should be putting in to the alert() call to display the contents of each cell of my HTML table? This should be in JS...can't use jQuery.

function GetCellValues() {
var table = document.getElementById('mytable');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
alert(table.rows[r].cells[c].innerHTML);
}
}
}

I know this is like years old post but since there is no selected answer I hope this answer may give you what you are expecting...
if(document.getElementsByTagName){
var table = document.getElementById('table className');
for (var i = 0, row; row = table.rows[i]; i++) {
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//columns would be accessed using the "col" variable assigned in the for loop
alert('col html>>'+col.innerHTML); //Will give you the html content of the td
alert('col>>'+col.innerText); //Will give you the td value
}
}
}
}

If I understand your question correctly, you are looking for innerHTML:
alert(col.firstChild.innerHTML);

confer below code
<html>
<script>
function addRow(){
var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e =table.rows.length-1;
var l =table.rows[e].cells.length;
//x.innerHTML = " ";
for (var c =0, m=l; c < m; c++) {
table.rows[0].insertCell(c);
table.rows[0].cells[c].innerHTML = " ";
}
}
function addColumn(){
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].insertCell(0);
table.rows[r].cells[0].innerHTML = " " ;
}
}
function deleteRow() {
document.getElementById("myTable").deleteRow(0);
}
function deleteColumn() {
// var row = document.getElementById("myRow");
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].deleteCell(0);//var table handle
}
}
</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
<input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
<input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
<input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>
<table id='myTable' border=1 cellpadding=0 cellspacing=0>
<tr id='myRow'>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>

The code yo have provided runs fine. Remember that if you have your code in the header, you need to wait for the dom to be loaded first. In jQuery it would just be as simple as putting your code inside $(function(e){...});
In normal javascript use window.onLoad(..) or the like... or have the script after the table defnition (yuck!). The snippet you provided runs fine when I have it that way for the following:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<table id='ddReferences'>
<tr>
<td>dfsdf</td>
<td>sdfs</td>
<td>frtyr</td>
<td>hjhj</td>
</tr>
</table>
<script>
var refTab = document.getElementById("ddReferences")
var ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; row = refTab.rows[i]; i++ ) {
row = refTab.rows[i];
for ( var j = 0; col = row.cells[j]; j++ ) {
alert(col.firstChild.nodeValue);
}
}
</script>
</body>
</html>

the above guy was close but here is what you want:
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
alert(table.rows[r].cells[c].firstChild.value);
}
}
}catch(e) {
alert(e);
}

If you are looking for the contents of the TD (cell), then it would simply be: col.innerHTML
I.e: alert(col.innerHTML);
You'll then need to parse that for any values you're looking for.

Have you tried innerHTML?
I'd be inclined to use getElementsByTagName() to find the <tr> elements, and then on each to call it again to find the <td> elements. To get the contents, you can either use innerHTML or the appropriate (browser-specific) variation on innerText.

A few problems:
The loop conditional in your for statements is an assignment, not a loop check, so it might infinite loop
You should use the item() function on those rows/cells collections, not sure if array index works on those (not actually JS arrays)
You should declare the row/col objects to ensure their scope is correct.
Here is an updated example:
var refTab=document.getElementById("ddReferences")
var ttl;
// Loop through all rows and columns of the table and popup alert with the value
// /content of each cell.
for ( var i = 0; i<refTab.rows.length; i++ ) {
var row = refTab.rows.item(i);
for ( var j = 0; j<row.cells.length; j++ ) {
var col = row.cells.item(j);
alert(col.firstChild.innerText);
}
}
Replace innerText with innerHTML if you want HTML, not the text contents.

Guess I'm going to answer my own questions....Sarfraz was close but not quite right. The correct answer is:
alert(col.firstChild.value);

Try this out:
alert(col.firstChild.data)
Check this out for the difference between nodeValue and data:
When working with text nodes should I use the "data", "nodeValue", "textContent" or "wholeText" field?

<script>
$('#tinh').click(function () {
var sumVal = 0;
var table = document.getElementById("table1");
for (var i = 1; i < (table.rows.length-1); i++) {
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
document.getElementById("valueTotal").innerHTML = sumVal;
});
</script>

Related

how to find a td by index in jquery

how can i change the inner html by getting element by index
i want to change the content of cells according to their index values
<table>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</table>
function LFLS() {
// LFLS => load from local Storage
for (i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);//it return values like ("1,2","2,5", etc.)
console.log(key)
row = key.split(",")[0];
col = key.split(",")[1];
//how to get the cell by row and col
}
}
As Sakil said you can use eq(). Try this:
function LFLS() {
// load from local Storage
for (i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
row = key.split(",")[0];
col = key.split(",")[1];
// how to get the cell by row and col
$("table tr").eq(row).children().eq(col).html('NEW VALUE')
}
}
I believe you need the following snippets.
Before your for loop
const rows = $("table tr");
After you obtain row & col variables
const cellToUpdate = rows[row].children[col];
Alternatively, if you're looking to programatically loop through the table you could use the following snippet.
<script type="text/javascript">
const rows = $("table tr");
for( i = 0; i < rows.length; i++ ) {
const currRow = rows[i];
const rowChildren = currRow.children;
for( n = 0; n < rowChildren.length; n++ ) {
const cell = rowChildren[n];
cell.innerHTML = "My new data for row: " + i + " in cell " + n;
}
}
</script>
Is something on the lines of below not going to work for you for some reason?
$("table tr:nth-of-type([your-row])).eq([your-col]).html([your_content]);

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)

Populate table from array using JQuery

I have an array of 16 elements that I want to fill a table. I want it to have 2 rows with 8 cells in each row which is filled with the array. My problem is that when the table is populated, the table populates all elements into one row. I have not had much experience with JQuery and I want to try to get this to work. Any help is appreciated! Here is my code:
//**********Javascript & JQuery**********
var array = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8];
var count = 0;
var totalCells = 8;
function writeTable() {
var $table = $('#summaryOfResults');
//Array always includes enough elements to fill an entire row, which is 8 cells. Outer loop determines how many rows to make.
//Inner loop determines the elements to print in the cells for that row.
for (var i = 0; i < array.length / 8; i++) {
$table.find('#body').append('<tr>');
for (var j = 0; j < totalCells; j++) {
$table.append('<td>' + array[count] + '</td>');
count++;
}
$table.append('</tr>');
}
}
//**********HTML**********
<html>
<head>
</head>
<body>
<div id="resultsTable">
<table id='summaryOfResults' border='1'>
<tbody id="body">
<tr>
<th>#</th>
<th>n<sub>i</sub></th>
<th>n<sub>f</sub></th>
<th>E<sub>i</sub> (J)</th>
<th>E<sub>f</sub> (J)</th>
<th>ΔE (J)</th>
<th>ΔE (kJ/mol)</th>
<th>λ (nm)</th>
</tr>
</tbody>
</table>
</div>
<div id="tableButtons">
<button id='copyButton' onclick=''>Copy Table</button>
<button id='clear' onclick='clearTable();'>Clear Table</button>
<button id='write' onclick='writeTable();'>Write Table</button>
</div>
</body>
</html>
First, you have to reset count on every click.
Next, you have to specify where exactly the <td> elements have to be appended to. As for now, you're appending them directly to the <table> :
// your declaration of the table element:
var $table = $('#summaryOfResults');
// ...
// then in nested loop, you're appending the cells directly to the table:
$table.append('<td>' + array[count] + '</td>');
The last thing - .append('</tr>') is not a proper way to create an element object, it should be '<tr/>' , or '<tr></tr>'.
This should be what you're looking for:
function writeTable() {
// cache <tbody> element:
var tbody = $('#body');
for (var i = 0; i < array.length / 8; i++) {
// create an <tr> element, append it to the <tbody> and cache it as a variable:
var tr = $('<tr/>').appendTo(tbody);
for (var j = 0; j < totalCells; j++) {
// append <td> elements to previously created <tr> element:
tr.append('<td>' + array[count] + '</td>');
count++;
}
}
// reset the count:
count = 0;
}
JSFiddle
Alternatively, make a HTML string and append it to the table outside of the loop:
function writeTable() {
// declare html variable (a string holder):
var html = '';
for (var i = 0; i < array.length / 8; i++) {
// add opening <tr> tag to the string:
html += '<tr>';
for (var j = 0; j < totalCells; j++) {
// add <td> elements to the string:
html += '<td>' + array[count] + '</td>';
count++;
}
// add closing </tr> tag to the string:
html += '</tr>';
}
//append created html to the table body:
$('#body').append(html);
// reset the count:
count = 0;
}
JSFiddle

How to create a table using a loop?

The individual table rows are giving me a problem. I have created what I want using divs but I need to use a table instead of divs. My table has 220 cells, 10 rows, and 22 columns. Each cell has to have the value of i inside the innerHTML. Here is similar to what i want using Divs ( although the cell height and width does not have to be set ):
<!DOCTYPE html>
<html>
<head>
<style>
#container{
width:682px; height:310px;
background-color:#555; font-size:85%;
}
.cell {
width:30px; height:30px;
background-color:#333; color:#ccc;
float:left; margin-right:1px;
margin-bottom:1px;
}
</style>
</head>
<body>
<div id="container">
<script>
for( var i = 1; i <= 220; i++ ){
document.getElementById( 'container' ).innerHTML +=
'<div class="cell">' + i + '</div>'
}
</script>
</div>
</body>
</html>
http://jsfiddle.net/8r6619wL/
This is my starting attempt using a table:
<script>
for( var i = 0; i <= 10; i++ )
{
document.getElementById( 'table' ).innerHTML +=
'<tr id = "row' + i + '"><td>...</td></tr>';
}
</script>
But that code somehow dynamically creates a bunch of tbody elements. Thanks for help as I newb
You can do this with nested loops - one to add cells to each row and one to add rows to the table. JSFiddle
var table = document.createElement('table'), tr, td, row, cell;
for (row = 0; row < 10; row++) {
tr = document.createElement('tr');
for (cell = 0; cell < 22; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = row * 22 + cell + 1;
}
table.appendChild(tr);
}
document.getElementById('container').appendChild(table);
Alternatively, you can create an empty row of 22 cells, clone it 10 times, and then add the numbers to the cells.
var table = document.createElement('table'),
tr = document.createElement('tr'),
cells, i;
for (i = 0; i < 22; i++) { // Create an empty row
tr.appendChild(document.createElement('td'));
}
for (i = 0; i < 10; i++) { // Add 10 copies of it to the table
table.appendChild(tr.cloneNode(true));
}
cells = table.getElementsByTagName('td'); // get all of the cells
for (i = 0; i < 220; i++) { // number them
cells[i].innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);
And a third option: add the cells in a single loop, making a new row every 22 cells.
var table = document.createElement('table'), tr, td, i;
for (i = 0; i < 220; i++) {
if (i % 22 == 0) { // every 22nd cell (including the first)
tr = table.appendChild(document.createElement('tr')); // add a new row
}
td = tr.appendChild(document.createElement('td'));
td.innerHTML = i + 1;
}
document.getElementById('container').appendChild(table);
Edit - how I would do this nowadays (2021)... with a helper function of some kind to build dom elements, and using map.
function make(tag, content) {
const el = document.createElement(tag);
content.forEach(c => el.appendChild(c));
return el;
}
document.getElementById("container").appendChild(make(
"table", [...Array(10).keys()].map(row => make(
"tr", [...Array(22).keys()].map(column => make(
"td", [document.createTextNode(row * 22 + column + 1)]
))
))
));
There are a lot of ways to do this, but one I've found to be helpful is to create a fragment then append everything into it. It's fast and limits DOM re-paints/re-flows from a loop.
Take a look at this jsbin example.
Here's the modified code:
function newNode(node, text, styles) {
node.innerHTML = text;
node.className = styles;
return node;
}
var fragment = document.createDocumentFragment(),
container = document.getElementById("container");
for(var i = 1; i <= 10; i++) {
var tr = document.createElement("tr");
var td = newNode(document.createElement("td"), i, "cell");
tr.appendChild(td);
fragment.appendChild(tr);
}
container.appendChild(fragment);
You can modify whatever you want inside the loop, but this should get you started.
That's because the DOM magically wraps a <tbody> element around stray table rows in your table, as it is designed to do. Fortunately, you can rewrite your loop in a way that will add all of those table rows at once, rather than one at a time.
The simplest solution to achieve this would be to store a string variable, and concatenate your rows onto that. Then, after you've concatenated your rows together into one string, you can set the innerHTML of your table element to that one string like so:
<script>
(function() {
var rows = '';
for( var i = 0; i <= 10; i++ )
{
rows += '<tr id = "row' + i + '"><td>...</td></tr>';
}
document.getElementById( 'table' ).innerHTML = rows;
}());
</script>
Here's a JSFiddle that demonstrates what I've just written. If you inspect the HTML using your browser's developer tools, you'll notice that one (and only one) tbody wraps around all of your table rows.
Also, if you're wondering, the odd-looking function which wraps around that code is simply a fancy way of keeping the variables you've created from becoming global (because they don't need to be). See this blog post for more details on how that works.
please check this out.
This is a very simple way to create a table using js and HTML
<body>
<table cellspacing="5" >
<thead>
<tr>
<td>Particulate count</td>
<td>Temperature</td>
<td>Humidity</td>
</tr>
</thead>
<tbody id="xxx">
</tbody>
</table>
<script>
for (var a=0; a < 2; a++) {
var table1 = document.getElementById('xxx');
var rowrow = document.createElement('tr');
for ( i=0; i <1; i++) {
var cell1 = document.createElement('td');
var text1 = document.createTextNode('test1'+a);
var cell2 = document.createElement('td');
var text2 = document.createTextNode('test2'+a);
var cell3 = document.createElement('td');
var text3 = document.createTextNode('test3'+a);
cell1.appendChild(text1);
rowrow.appendChild(cell1);
cell2.appendChild(text2);
rowrow.appendChild(cell2);
cell3.appendChild(text3);
rowrow.appendChild(cell3);
}
table1.appendChild(rowrow);
}
</script>
</body>
</html>

How to put the elements of array of arrays in table cells?

<html>
<head>
<title>Array of Arrays</title>
<script type="text/javascript">
function matrix()
{
var e=prompt("Cols?",0);
var f=prompt("Rows?",0);
var matrix = new Array();
for (var i=0;i<e;i++)
{
matrix[i] = new Array();
for (var j=0;j<f;j++)
{
matrix[i][j]=Math.floor((Math.random()*1000)+1);
}
}
for (var i=0; i<=e-1; i++)
{
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"<tr>";
for (var j=0; j<=f-1; j++)
{
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"<td>"+matrix[i][j]+"</td>";
}
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"</tr>";
}
document.getElementById("keret").innerHTML=
document.getElementById("keret").innerHTML+"</table>";
}
</script>
</head>
<body onload="matrix()">
<table border="1" id="keret">
</body>
</html>
This script makes a user defined array of arrays, and filling it up with random numbers. My problem is:
I can't make the script to put the values in dividual cells.
Your second loop can be as follows:
for (var i = 0; i < e; i++) {
var row = document.createElement("tr");
for (var j = 0; j < f; j++) {
var cell = document.createElement("td");
cell.innerHTML = matrix[i][j];
row.appendChild(cell);
}
document.getElementById("keret").appendChild(row);
}
This appends a tr element for each row and a td element for each column within the row. Then it appends the row to your table. Your HTML would be slightly modified as well:
<table border="1" id="keret"></table>
(Rows & Columns prompts need to be switched but I didn't want to mess up your variable names).
Fiddle: http://jsfiddle.net/verashn/7Rwnc/
<html>
<head>
<title>Array of Arrays</title>
<script type="text/javascript">
function matrix() {
var e = prompt("Cols?",0),
f = prompt("Rows?",0),
allRows = [],
row = [];
for (var i = 0; i < e; i += 1) {
row = ['<tr>', '</tr>']; // this serves as your initial template
for (var j = 0; j < f; j += 1) {
// now create the columns
row.splice(-1, 0, '<td>' + Math.floor((Math.random()*1000)+1) + '</td>')
}
allRows.push(row.join(''));
}
document.getElementById("keret").innerHTML = allRows.join('');
}
</script>
</head>
<body onload="matrix()">
<table border="1" id="keret"></table>
</body>
</html>

Categories

Resources