Countng number of rows of table and getting every cell value - javascript

My question is that I have found the code to traverse every row and cell but I am not able to understand how do i fetch every cell value with this code ? Can anyone help me with this code. I want to use this code only in my project.
Here is my js code
var table = document.getElementById('tblOne');
var rowCount = $('.table tr').length - 1;
for(var i=0; i<rowCount; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
console.log(cell);
//do something with every cell here
}
}

Following will help
var cell = row.cells[y];
console.log($(cell).text());

Related

Cannot read property 'rowIndex' of undefined for my javascript code

<script>
var cell = document.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
cell[i].onclick = function(){alert("Hello world");};
var col = this.cellIndex;
var row = this.parentNode.rowIndex;
}
</script>
So I have a table, a HTML table. And I am trying to get the column and row of the part of the table that was clicked on, and I am using cell index, and row index. However this is not working and is pulling up the error " cannot read property rowindex of undefined" i couldnt find this error anywhere online..
As referenced in comments, this will reference the window inside of a for loop, additionally, you're creating your function for alert within the for loop, not something you want to do as this may create weird behaviors. I think what you're trying to achieve will work better with the code below. Tip, unless you need the index you should take advantage of the much simpler "for of" loop.
function createAlert(td) {
alert("Hello world")
var col = this.cellIndex;
var row = this.parentNode.rowIndex;
console.log('the col and row:::::', col, row)
}
var cell = document.getElementsByTagName("td");
for (let td of cell) {
td.onclick = createAlert
}
<table>
<td>hello</td>
<td>hello2</td>
<td>hell3</td>
<td>hello4</td>
<td>5 hello</td>
<td>hello6</td>
</table>

Remove all child nodes but the first one

I have an HTML table. The first row contains a checkbox. There is a javascript method associated to the checkbox change. If the checkbox is checked, the code adds a few rows to the table and fills them. If the checkbox is unchecked, the code removes all rows but the first one (the one that contains the checkbox).
The first part of the code works fine : the rows are properly added.
I have an issue with the second part. Here is my code :
if (checkboxValue) {
//Add first row
var tr1 = document.createElement("tr");
var td1_1 = document.createElement("td");
....
tr1.appendChild(td1_1);
var td1_2 = document.createElement("td");
...
tr1.appendChild(td1_2);
table.appendChild(tr1);
//Add second row
var tr2 = document.createElement("tr");
var td2_1 = document.createElement("td");
...
tr2.appendChild(td2_1);
var td2_2 = document.createElement("td");
...
tr2.appendChild(td2_2);
table.appendChild(tr2);
} else {
//Remove all rows but the first
var rows = table.getElementsByTagName("tr");
var nbrRows = rows.length;
if (nbrRows > 1) {
for (var i = 1; i < nbrRows; i++) {
var row = rows[i];
row.parentNode.removeChild(row);
}
}
}
The issue always come from rows[2] being undefined. I have no idea why!
If, instead of using removeChild, I write row.innerHTML = "", I have the visual effect I am looking for (all rows gone), but this is inelegant, since the table now contains several empty rows (their number increasing everytime I check/uncheck the checkbox).
A clue? Thank you very much for your time!
Don't use for-loop to remove DOM elements like this. The problem is that rows is a live collection, meaning that it updates every time you remove elements from DOM. As the result, i counter shifts and eventually you hit "undefined" element spot.
Instead, use while loop. For example, to remove all rows except the first one you could do:
var rows = table.getElementsByTagName("tr");
while (rows.length > 1) {
rows[1].parentNode.removeChild(rows[1]);
}
Also note, that it's getElementsByTagName without s.
UPD. Or iterate backward if you like for-loops better:
var rows = table.getElementsByTagName("tr");
for (var i = rows.length - 1; i > 0; i--) {
rows[i].parentNode.removeChild(rows[i]);
}
Demo: https://jsfiddle.net/9y03co6w/
you remove a row from the array you are iterating over. This is always a bad idea and probably the reason for your error.
solution: start iterating from the end instead of the beginning.
also see for example: example
try to replace this line
var rows = table.getElementsByTagNames("tr");
by
var rows = table.find("tr");

Create an array from JSON in Javascript

I've researched quite a bit on here and I can't seem to find something that will work for me. What I have is an application that I'm trying to have go out and return the next four bus arrival times for a bus stop. I am reaching out to an API that returns this data in a JSON file. The problem I am having is I can see my request go out via fiddler but I can't seem to get the data into an array. Below is the code that I'm dealing with right now. I'm trying to get the returned data into a table format which you can see I'm failing at.
Eventually I want to get a popup to appear when the user clicks on the Show me the next 4 bus arrival times but this was for testing purposes. I would love to have the users click on my button which calls this function and then something like a like table open with these values. If you can help with that within this code I would appreciate it as well.
JSON Data:
[{"ARRIVAL":"01:23P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"01:53P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"02:23P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"02:53P","ROUTE":"208","DIR":"E"}]
Code:
<script>
function getTimes(stopNumber) {
var busArrivalAPI = "http://blahblahblah/rtcTimes/" + stopNumber ";
$.getJSON(busArrivalAPI, function(busArrivals) {
var a = [];
for (var i = 0; i < busArrivals.length; i++) {
a[i] = [busArrivals[i].ROUTE, busArrivals[i].ARRIVAL, busArrivals[i].DIR];
document.getElementById("results").createElement("TR");
for (var b = 0; b < 3; b++) {
var x = document.createElement("TH");
var z = a[i][b];
var t = document.createTextNode(z);
x.appendChild(t);
document.getElementById('results').appendChild(x);
};
};
});
</script>
My DIV:
<div style="overflow-x:scroll; overflow-y:scroll;" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="title:'Bus Arrival Times', selected:true">
<table id = 'results'>
<tr>
<th>Route</th>
<th>Arrival Time</th>
<th>Direction</th>
</tr>
</table>
</div>
UPDATE: Ok, I've use the makeTable idea provide below and it works when I program as seen below hard coding the json data. However, when trying to use the $.getJSON I'm having some cross domain issues now and don't know how I can get my $.getJSON request working. Any input on how to get the data from my getJSON request work be great.
function getTimes(stopNumber) {
// This is the API address I need to hit. Trying to figure out how to incorporate that and remove the function getJSON where I have the data hard coded.
//var busArrivalAPI = "http://-----/rtcTimes/"+ stopNumber + "?jsoncallback=?";
function makeTable(busArrivals) {
// This will remove old values so table will only load current Times
var results = document.getElementById("results");
var rowCount = results.rows.length;
for (var x=rowCount-1; x>0; x--) {
results.deleteRow(x);
}
// This will populate the result table with the correct bus routes/times/direction
busArrivals.forEach(function(busArrival) {
var tr = document.createElement('tr');
var route = document.createElement('td');
route.appendChild(document.createTextNode(busArrival.ROUTE));
var arrival = document.createElement('td');
arrival.appendChild(document.createTextNode(busArrival.ARRIVAL));
var direction = document.createElement('td');
direction.appendChild(document.createTextNode(busArrival.DIR));
tr.appendChild(route);
tr.appendChild(arrival);
tr.appendChild(direction);
document.getElementById('results').appendChild(tr);
});
}
function getJSON(callback) {
var data = [{"ARRIVAL":"05:23P","ROUTE":"201","DIR":"E"},
{"ARRIVAL":"05:54P","ROUTE":"202","DIR":"E"},
{"ARRIVAL":"06:33P","ROUTE":"203","DIR":"E"},
{"ARRIVAL":"07:11P","ROUTE":"204","DIR":"E"}];
callback(data);
}
getJSON(makeTable);
};
I think you could write a separate function to build the table, like this:
function makeTable(busArrivals) {
busArrivals.forEach(function(busArrival) {
var tr = document.createElement('tr');
var route = document.createElement('td');
route.appendChild(document.createTextNode(busArrival.ROUTE));
var arrival = document.createElement('td');
arrival.appendChild(document.createTextNode(busArrival.ARRIVAL));
var direction = document.createElement('td');
direction.appendChild(document.createTextNode(busArrival.DIR));
tr.appendChild(route);
tr.appendChild(arrival);
tr.appendChild(direction);
document.getElementById('results').appendChild(tr);
});
}
var busArrivalAPI = 'http://blahblahblah/rtcTimes/'+ stopNumber;
$.getJSON(busArrivalAPI, makeTable);
In each iteration of the forEach loop, you construct a tr element, insert the tds and finally put the whole thing inside the DOM.
You're creating a TR element, but never appending it to the table. Instead, you're appending the TH elements directly to the table, which is invalid.
function getTimes(stopNumber) {
var busArrivalAPI = "http://blahblahblah/rtcTimes/" + stopNumber;
$.getJSON(busArrivalAPI, function(busArrivals) {
var table = document.getElementById('results');
for (var i = 0; i < busArrivals.length; i++) {
var a = [busArrivals[i].ROUTE, busArrivals[i].ARRIVAL, busArrivals[i].DIR];
var row = document.createElement("TR");
for (var b = 0; b < 3; b++) {
var x = document.createElement("TH");
var z = a[b];
var t = document.createTextNode(z);
x.appendChild(t);
row.appendChild(x);
};
table.appendChild(row);
};
});
}
I'm not sure why you need the a array. If you just want to change get the object properties into an array so you can iterate over it, you can do that with a 1-dimensional array, you don't need to save all the other rows in a 2-dimensional array. I've changed a to a single array.

set limit for the number of columns per row in a html table

May I know what are the ways to limit the number of columns of a Html table (e.g. 3 columns per row)?
FYI, I'm using row.insertCell() to add cells to a particular row with matching the row id. I wish to limit the cell number to only 3 per row in the table.
"Limit"? There's no natural limit. You'll have to enforce it yourself on your own code.
Check if the row you're inserting into already has 3 cells, and don't add a new one if it does.
Use row.cells collection to check, how many cells a row contains.
var row = document.getElementById('row_id'),
cells = row.cells, max = 3;
if (cells.length < max) {
// Add cell(s) to #row_id
}
There is no such limit in the javascript or html standard. you have to enforce it yourself as a rule during the insertion.
A simple counter does the trick.
var items = ['c00', 'c01', 'c02', 'c10', 'c11', 'c12']; //sample data
var table = document.getElementById("myTable");
var row;
for(var i = 0; i < items.length; i++){
if(i % 3 == 0) { //after every third cell add a new row and change the row variable to point to it
row = table.insertRow(-1);
}
var cell = row.insertCell(-1); //simply insert the row
cell.innerHTML = items[i];
}
there are a number of ways of doing it. it will really depend on how you structure your code.
for(i=0;i<3;i++)
row.insertCell()

Deleting table rows in javascript

I'm having trouble with a function in javascript and can't figure out why. It's really quite straight forward. I'm trying to delete all the rows in a html table. so I wrote:
function delete_gameboard(){
var table = document.getElementById("gameboard");
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
table.deleteRow(i);
}
}
Yet, it'll only delete half of them. Can anyone see what's causing this strange behavior?
Because when you delete the first row, the second row will become the first, it's dynamic.
You could do like:
while(table.rows.length > 0) {
table.deleteRow(0);
}
Consider this:
index 0: row #1
index 1: row #2
index 2: row #3
index 3: row #4
index 4: row #5
you delete index #2 (row #3), so the DOM engine adjusts the index keys and you end up with:
index 0: row #1
index 1: row #2
index 2: row #4 <---hey! index #2 is still there
index 3: row #5
You're basically digging a hole in the spot where you're standing, so as you dig deeper, you naturally sink deeper and never see any progress... until you run out of rows to delete in the table.
function delete_gameboard(){
var table = document.getElementById("gameboard");
var rowCount = table.rows.length;
for (var i=rowcount-1; i >=0; i--) {
table.deleteRow(i);
}
}
The index of the row changes when you delete it. Use a reverse loop. This will also be helpful if you are using any condition to delete rows. If you are deleting all rows,use the following
while(table.rows.length) {
table.deleteRow(0);
}
If you delete the first row, the second row becomes the new first row.
I prefer to do this:
while(table.rows[0]) table.deleteRow(0);
You could just go:
document.getElementById("gameboard").innerHTML = "";
The table rows is live, that is if you delete row 0 then the next row becomes row 0, just constantly delete row 0
function delete_gameboard(){
var table = document.getElementById("gameboard");
var rowCount = table.rows.length;
for (var i=0; i < rowCount; i++) {
table.deleteRow(0);
}
}
function delRow()
{
var current = window.event.srcElement;
//here we will delete the line
while ( (current = current.parentElement) && current.tagName !="TR");
current.parentElement.removeChild(current);
}
If you are using JQuery in your code then the easiest way to delete the rows is using the following code:
$('#myTable tbody').html('');

Categories

Resources