Adding table rows and cells - javascript

I tried to make the page add rows and five cells to each table, however I'm having some problems. I appended the row first to the table then followed by looping through the and adding five cells to each row, however whenever I ran it in my web browser it produced this:
I want the cells to be a child of the table row.
function addRows(ramnt) {
if(ramnt > 0){
var cellcount = 5;
var tccount = 0;
table.append('<tr>');
console.log('Appended <tr>');
while(tccount < cellcount){
tccount = tccount + 1;
table.append('<td id="Cell-' + tccount + '" class="gencell"></td>');
}
if (tccount = cellcount){
table.append('</tr>');
ramnt = ramnt - 1;
addRows(ramnt);
}
}
}
console.log('Working');
var table = $('Table');
addRows(5);

I would advise making your function a little more dynamic. Here is what I would suggest:
function addRows(rc, to) {
if(rc > 0){
var cellcount = 5;
for(var i = 0; i < rc; i++){
var row = $("<tr>", { id: "Row-" + i });
for(var c = 0; c < cellcount; c++){
row.append("<td id='Cell-" + c + "' class='gencell'></td>");
}
to.append(row);
console.log("Row " + i + " created");
}
return true;
} else {
return false;
}
}
Then you can pass the Number of Rows and the Table Object like so:
addRows(5, $("table"));
As I said, I would advise setting your table like so:
<table id="myTable"></table>
This way if you later add another table or do something differnt, you can still use the same code:
addRows(5, $("#myTable"));
Working Example: https://jsfiddle.net/Twisty/Lysr2n5v/
You can take a bit further to write to function to accept X number of Rows, N number of Cells per Row, and the table Object: https://jsfiddle.net/Twisty/Lysr2n5v/2/
function addRows(rc, cc, to) {
if(rc > 0){
for(var i = 0; i < rc; i++){
var row = $("<tr>", { id: "Row-" + i });
for(var c = 0; c < cc; c++){
row.append("<td id='Cell-" + c + "' class='gencell'></td>");
}
to.append(row);
console.log("Row " + i + " created");
}
return true;
} else {
return false;
}
}

When you call table.append('<tr>'), jQuery inserts both opening and closing tags. I tried this:
Then you call table.append('<td id="Cell-' + tccount + '" class="gencell"></td>');, which appends the td element at the end of the table, so it goes after the tr you appended before.
What you need to do is insert the tr as you did, but then select this tr and append into it. So something like this:
table.find('tr:last').append('<td id="Cell-' + tccount + '" class="gencell"></td>');

You need to create a row, append all the columns to that row, then append the row to the table like below.
I would also recommend adding logic to check the number of columns already present in the table and make sure you dont add more than are there now as that would not be valid.
With the below:
addRows(5,5) - will add 5 rows to every table on the page where each row will the same number of columns as the table currently has or 5 columns if the table doesnt currently have any columns
addRows(5,5,'#myTable') - will add 5 rows to the table with the id myTable where each row will the same number of columns as the table currently has or 5 columns if the table doesnt currently have any columns
function addRows(rowCount, colCount, table) {
var $tables= table ? $(table) : $('table');
$tables.each(function(){
console.log('table');
$this=$(this);
colCount =$this.find('tr:eq(0)').find('td').length || colCount // limit the number of added cols to the numer already present
for(r=0;r<rowCount;r++){
var $row=$('<tr>');
for(c=0;c<colCount;c++){
$row.append('<td>');
}
$this.append($row);
}
});
}
addRows(5,5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1"></table>
<br>
<br>
<br>
<br>
<br>
<table border="1"><tr>
<td>some content</td>
<td>some content</td>
<td>some content</td>
</tr></table>

Related

Find values in table cells with Javascript

I'm using a dynamic table in HTML, but I need to verify the values are not repeated. I'm trying to do it with the value inside the cell rather than the text. These are the values and what I have so far:
var tBody = $("#tablaAplicaciones > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add Name cell.
var cell = $(row.insertCell(-1));
cell.html(nameCountry);
cell.val(idCountry);
//Add Country cell.
cell = $(row.insertCell(-1));
cell.html(nameCompany);
cell.val(idCompany);
if (($('#tablaApp tr > td:contains(' + countryName + ') + td:contains(' + companyName + ')').length) == 1) {
.
.
.
}
Welcome to Stack Overflow. Consider the following code.
$(function() {
var idCountry = "9";
var nameCountry = "United States";
var idCompany = "9";
var nameCompany = "Genentech";
var tBody = $("#tablaAplicaciones > tbody");
//Create Row
var row = $("<tr>");
//Add Country cell to Row
$("<td>", {
class: "name-country"
})
.data("id", idCountry)
.html(nameCompany)
.appendTo(row);
//Add Company cell to Row
$("<td>", {
class: "name-company"
})
.data("id", idCompany)
.html(nameCompany)
.appendTo(row);
// Assume vales are not in the table
var found = -1;
$("tr", tBody).each(function(i, el) {
// Test each row, if value is found set test to tue
if ($(".name-country", el).text().trim() == nameCountry) {
found = i;
}
if ($(".name-company", el).text().trim() == nameCompany) {
found = i;
}
});
if (found == -1) {
// If test is false, append the row to table
row.appendTo(tBody);
console.log("Row Added", row);
} else {
console.log("Values already in Table, row: " + found);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tablaAplicaciones">
<thead>
<tr>
<th>Country</th>
<th>Company</th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="1" class="name-country">United States</td>
<td data-id="1" class="name-company">Apple Inc.</td>
</tbody>
</table>
Using .each(), you can iterate over each row and compare the values. A variable can be used as a flag to indicate if the needle was found in the haystack. If not found, you can append the row. Otherwise, do not add the row.
Hope that helps.

Dynamically populate data into table using JavaScript

I am trying to populate table data dynamically in JavaScript. I managed to populate it but there is some problem with the styling, here is what I have achieved so far:
And my code to achieve the above:
function populateOverallOverview(result){
var tableData = new Array();
var table = document.getElementById("firstTabOverall");
for(var i = 0; i < result.length; i++){
tableData[i] = new Array('Category: ' + result[i].category + '\n Best selling month: ' + result[i].topMonthStr + '\n Amount: ' + result[i].topAmount.toFixed(2));
}
for(var i = 0; i < tableData.length; i++){
var newRow = table.insertRow(table.length);
for(var j = 0; j < tableData[i].length; j++){
var cell = newRow.insertCell(j);
cell.innerHTML = tableData[i][j];
}
}
}
My HTML code:
<div class="col-md-6">
<table id="firstTabOverall" class="table table-striped" style="font-size:13px">
</table>
</div>
What I wanted to achieve is for each row, there will be 3 different sub-rows for category, best selling month and amount. I am trying to split them into the next line using '\n' but it does not work.
Also, is there any way to bold the category, best selling month and amount wording in this case?
You do quite some unnecessary shifting-around of data. From results into a temp array, from the temp array into the table... why not from results straight into the table? Also, of course \n does not work. Line breaks mean nothing in HTML. You must add each cell individually.
The following looks a lot more straight-forward – and the Array#forEach() method rids you of the need for a separate loop counter, too:
function populateOverallOverview(result){
var table = document.getElementById("firstTabOverall");
// helper function
function addCell(tr, text) {
var td = tr.insertCell();
td.textContent = text;
return td;
}
// insert data
result.forEach(function (item) {
var row = table.insertRow();
addCell(row, 'Category: ' + item.category);
addCell(row, 'Best selling month: ' + item.topMonthStr);
addCell(row, 'Amount: ' + item.topAmount.toFixed(2));
});
}
Instead of repeating the category names in front of the values, write them into the header row. That's how a table is supposed to work anyway, right?
So, maybe this is better:
function populateOverallOverview(result){
var table = document.getElementById("firstTabOverall");
// helper function
function addCell(tr, text) {
var td = tr.insertCell();
td.textContent = text;
return td;
}
// create header
var thead = table.createTHead();
var headerRow = th.insertRow();
addCell(headerRow, 'Category');
addCell(headerRow, 'Best selling month');
addCell(headerRow, 'Amount');
// insert data
result.forEach(function (item) {
var row = table.insertRow();
addCell(row, item.category);
addCell(row, item.topMonthStr);
addCell(row, item.topAmount.toFixed(2));
});
}
Use CSS to style your table and table header. It might be easier to just write the header row into the static HTML source up-front.
If you positively must add bold text inline labels, you could use these document.createElement("b"), to get a <b> element, set its .textContent and then use .appendChild() of the respective container, in this case of the table cell.
You can add plain text the same way - just use document.createTextNode('...your text...') instead and append that.

How can I delete specific rows from a table?

I have a table with n number of rows. The value of n changes/updates every minute.
The first <td> of every row will either contain some text, or it will be blank.
I want to delete/remove all the rows except, the first row and the row whose first cell contains the text 'xyz'.
So, how will I be able to do this?
This table element is stored in the variable parentTable.
I'm kind of new to javascript and programming. Any help would be appreciated. Thanks.
I tested it with just the second row, but nothing happened even though the text is not xyz in the cell.
if(parentNode.childNodes[1].innerText !== "xyz")
parentTable.deleteRow[1];
And how do I loop around every row and do this?
EDIT: HTML for first cell in every row.
<td class=wbwhite align=center width=40 style="border-top: none; border-left:none; border-right:none;">
<a href="www.kasdjfkasd.sadsdk.comi" class=pi>xyz</a>
</td>
Try this:
var table = parentTable;
var rowCount = table.rows.length;
for ( var i = 1; i < rowCount; i++ )
{
var row = table.rows[i];
var val= row.cells[0].childNodes[0].innerHTML.toString();
if ( 'xyz' != val )
{
table.deleteRow( i );
rowCount--;
i--;
}
}
Use this code (pure JavaScript):
(assuming table has id = tableId).
var all = document.querySelectorAll('#tableId > tbody > tr');
// i = 1 not i = 0 to keep the first row.
for (var i = 1; i < all.length; i++) {
var td = all[i].querySelectorAll('td')[0];
if ( td.textContent != "xyz" ) {
all[i].parentNode.removeChild(all[i]);
}
}
You can try this
var allRows = parentTable.getElementsByTagName('TR');
for(var i=1; i<allRows.length;)
{
var tr = allRows[i];
var firstTd = tr.getElementsByTagName('TD')[0];
if(firstTd.innerHTML !== 'xyz')
{
tr.parentNode.removeChild(tr);
}else{
i++;
}
}

Finding a colSpan Header for one of the cells or td's is Spans

I have multiple column headers that spans of multiple column and I would like to find the correct header number/count for the columns.
I want to enter a column number and get the header: example column 5 is RDataTest6 $('td.eq(5)) and its header is HTest3 $('th.eq(2))
Example:
<table>
<tr>
<th>HTest1</th>
<th colSpan="2">HTest2</th>
<th colSpan="4">HTest3</th>
<th colSpan="2">HTest4</th>
</tr>
<tr>
<td>RDataTest1</td>
<td>RDataTest2</td>
<td>RDataTest3</td>
<td>RDataTest4</td>
<td>RDataTest5</td>
<td>RDataTest6</td>
<td>RDataTest7</td>
<td>RDataTest8</td>
<td>RDataTest9</td>
</tr>
</table>
​
Edit: You should implement a simple array that hold the header location, see below,
var thLocator = [], colCount = 1;
$table.find('tr:first th').each(function () {
for (var i = 0; i < this.colSpan; i++) {
thLocator.push(colCount);
}
colCount++;
});
$table.find('td').click(function () {
alert(thLocator[$(this).index()]);
});
And then anytime You can get the location of a td column. See DEMO -> Click on any TD to identify its col head position.
I am not sure which count you want so I wrote down all col count. See DEMO
$(function() {
var $table = $('table');
alert('Table Header Count ' + $table.find('tr:first th').length);
var thCount = 0;
$table.find('tr:first th').each(function () {
thCount += this.colSpan;
});
alert('Computed TH Count ' + thCount );
alert('Table TD Col Count ' + $table.find('tr:eq(1) td').length);
});
That's easy, as long as you don't have any rowspans:
function getCell(tr, col) {
var cell = tr.firstElementChild;
while (cell && (col -= cell.colSpan || 1)>=0)
cell = cell.nextElementSibling;
return cell;
}
See demonstration.

remove/hide table's empty column(s), including <th>

How can I hide the column with all empty cells including the title <th> in that column, while leaving the other columns and their titles as it is. Following jquery hides the entire <th>, which is not I want. Here is a sample, where I want to hide only the entire 'Column3' including <th>. Many thanks in advance.
$('table#mytable tr').each(function() {
if ($(this).children('td:empty').length === $(this).children('td').length) {
$(this).hide();
}
});
Took a while to piece together. Thanks to nxt for some of the code.
$('#mytable th').each(function(i) {
var remove = 0;
var tds = $(this).parents('table').find('tr td:nth-child(' + (i + 1) + ')')
tds.each(function(j) { if (this.innerHTML == '') remove++; });
if (remove == ($('#mytable tr').length - 1)) {
$(this).hide();
tds.hide();
}
});
If you want to hide the column if all cells (ignoring the header) are empty, you could do something like:
$('#mytable tr th').each(function(i) {
//select all tds in this column
var tds = $(this).parents('table')
.find('tr td:nth-child(' + (i + 1) + ')');
//check if all the cells in this column are empty
if(tds.length == tds.filter(':empty').length) {
//hide header
$(this).hide();
//hide cells
tds.hide();
}
});
Sample: http://jsfiddle.net/DeQHs/
Sample 2 (adapted for jQuery > 1.7): http://jsfiddle.net/mkginfo/mhgtmc05/
None of the solutions here worked for me. This was what I used to hide empty columns with or without a text in the header:
$('table').each(function(a, tbl) {
var currentTableRows = $(tbl).find('tbody tr').length;
$(tbl).find('th').each(function(i) {
var remove = 0;
var currentTable = $(this).parents('table');
var tds = currentTable.find('tr td:nth-child(' + (i + 1) + ')');
tds.each(function(j) { if ($(this).text().trim() === '') remove++; });
if (remove == currentTableRows) {
$(this).hide();
tds.hide();
}
});
});
http://jsfiddle.net/nlovatt/JsLn8/
A multi-table example which avoids using the table id in the selectors
You need the next code:
HTML
<table id="mytable" border="1">
<thead>
<tr><th>Column1</th><th>Column2</th><th>Column3</th><th>Column4</th></tr>
</thead>
<tbody>
<tr class="data"><td>1st</td><td>1.1</td><td></td><td>1</td></tr>
<tr class="data"><td>2nd</td><td>2.01</td><td></td><td>2</td></tr>
<tr class="data"><td>3rd</td><td>3.001</td><td></td><td>3</td></tr>
<tr class="data"><td>4th</td><td>4.01</td><td></td><td>4</td></tr>
</tbody>
</table>
JavaScript
var $table = $('#mytable');
var thead = $table[0].tHead, tbody = $table[0].tBodies[0];
var colsLen = tbody.rows[0].cells.length, rowsLen = tbody.rows.length;
var hideNode = function(node) { if (node) node.style.display = "none"; };
for (var j = 0; j < colsLen; ++j) {
var counter = 0;
for (var i = 0; i < rowsLen; ++i) {
if (tbody.rows[i].cells[j].childNodes.length == 0) ++counter;
}
if (counter == rowsLen) {
for (var i = 0; i < rowsLen; ++i) {
hideNode(tbody.rows[i].cells[j]);
}
hideNode(thead.rows[0].cells[j]);
}
}
If the table data are from a MySQL query it possible to verify if a column is empty by using count on the field (count = 0 means that there are no values).
It is quite fastidious when you have many fields, and the IF condition is needed for the corresponding header and footer cells too. But it works...
if ($sum_field>'0') echo "<th>field</th>";
if ($sum_field>'0') echo "<td>" . $row['field'] . "</td>";
#nmat solution works fine but doesn't handle footers.

Categories