Rows are added in thead instead of tbody - javascript

The following HTML file contains an add button. When clicked, it should add a row. When I inspect the code, I find the rows added under the thead not the tbody tag. Why is that? how to avoid this?
addButton = document.getElementById("add-button");
table = document.getElementById("data-table");
addButton.addEventListener('click', add, false);
function add() {
var tableLength = table.length;
var row = table.insertRow(tableLength);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML = "col1";
col2.innerHTML = "col2";
}
var delLink = document.getElementById("delete-link");
delLink.addEventListener('click', del, false);
function del() {
var rowstoDelete = table.querySelectorAll("tbody tr");
[].slice.call(rowstoDelete).forEach(function(row) {
row.remove()
});
}
<table align="center" cellspacing=1 cellpadding=1 id="data-table" border=1 class="data-table">
<thead>
<tr id="head" class="head">
<th class="head">Name</th>
<th class="head">Action</th>
</tr>
<tr id="initial-row" class="initial-row">
<th><input type="text" id="text-field"></th>
<th><input type="button" class="add-button" id="add-button" value="Add"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<a id="delete-link" href="#"> Delete all rows Except the first two</a>

check my fiddle here
enter link description here
What you didnt did is to see specifically for tbody. Answered here How to insert row in HTML table body in javascript?
addButton=document.getElementById("add-button");
table=document.getElementById("data-table");
addButton.addEventListener('click',add,false);
function add()
{
var tableLength=table.length;
var row = table.getElementsByTagName('tbody')[0].insertRow(tableLength);
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
col1.innerHTML="col1";
col2.innerHTML="col2";
}
var delLink = document.getElementById("delete-link");
delLink.addEventListener('click',del,false);
function del()
{
var rowstoDelete = table.querySelectorAll("tbody tr");
[].slice.call(rowstoDelete).forEach(function(row) {
row.remove()
});
}

Related

How to count rows on dynamically created rows with javascript

I am trying to make a system where I can create new rows and delete them too, I would like to have a counter that counts the row number of each individual row.
Under "Num" I would like to have the row numbers displayed, but I can't figure out how to do so.
EDIT
I found a jQuery snippet that seems to count my first row, but not the newly created ones.
Updated Fiddle with jQuery snippet
Updated JS code with snippet in the top
See my fiddle here: https://jsfiddle.net/pr05dw6p/14/
HTML code:
<div class="row">
<div class="large-8 large-offset-2 columns">
<h2>This is the table</h2>
<form method="post">
<table id="myTable" class="hover large-12 columns">
<thead>
<tr>
<th>Num.</th>
<th>Name</th>
<th>Height</th>
<th>Width</th>
</tr>
</thead>
<tbody id="bannerTable">
<tr>
<td><p></p></td>
<td><input type="text" name="name"></td>
<td><input type="number" name="height"></td>
<td><input type="number" name="width"></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
<div class="row">
<div class="large-4 large-offset-2 columns">
<button class="button expanded" onclick="newRow()">Add new row</button>
</div>
<div class=" large-4 columns">
<button class="alert button expanded" onclick="deleteRow()">Delete latest row</button>
</div>
</div>
JS code:
//CREATE NEW BANNER - TABLE ROW COUNTER
$('#bannerTable tr').each(function(idx){
$(this).children().first().html(idx + 1);
});
//CREATE NEW BANNER - CREATE ROW
function newRow() {
var table = document.getElementById("bannerTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var element1 = document.createElement('p');
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement('input');
element2.type="text", name="name";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement('input');
element3.type="number", name="height";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement('input');
element4.type="number", name="width";
cell4.appendChild(element4);
}
//CREATE NEW BANNER - DELETE ROW
function deleteRow(){
var table = document.getElementById("bannerTable");
var rowCount = table.rows.length;
if(rowCount>1){
table.deleteRow(-1);
}
}
To count the rows you can use:
var row_count = $('#bannerTable tr').length;
you can call it at the end of newRow() and deleteRow() an append the result e.g. to a div.
You can get the length(count) of table rows as stated in other answers by using
table.getElementsByTagName("tr").length
This will get the count, and you can put it into the html of your generated p tag by calling element1.innerHTML = table.getElementsByTagName("tr").length
I would also suggest running your newRow() function on page initialization without a preset tr. The count of the rows will also help when you insert a row so that it always inserts a row AFTER the previously inserted row, keeps the Num. column nice and clean too.
Check out this updated fiddle: https://jsfiddle.net/pr05dw6p/19/
We need to do following changes :
Add 1 as default value in HTML in the P tag
In Javascript code we need count TR of table and put its value in table.insertRow(row_count); after that we need to increment value and add it to new <P> tag.
<tbody id="bannerTable">
<tr>
<td><p>1</p></td>
<td><input type="text" name="name"></td>
<td><input type="number" name="height"></td>
<td><input type="number" name="width"></td>
</tr>
</tbody>
Javascript Code
//CREATE NEW BANNER - CREATE ROW
function newRow() {
var table = document.getElementById("bannerTable");
var row_count = document.getElementById("bannerTable").rows.length;
var row = table.insertRow(row_count);
row_count = row_count+1;
var cell1 = row.insertCell(0);
var element1 = document.createElement('p');
element1.innerHTML = row_count;
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement('input');
element2.type="text", name="name";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement('input');
element3.type="number", name="height";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement('input');
element4.type="number", name="width";
cell4.appendChild(element4);
}
var row_count = $('#myTable tbody tr').length.length;
call this after the add and delete row function

How to hide and show table that is populated via a form

Below is a form when submitted displays the content in a table.
What works
Content is successfully transferred via form to table.
What is not working
I wanted to hide the table when the page loads and be displayed only after the form is submitted.
I tried #myTableData {visibility: hidden;} in css and then I tried plugging (.style.visibility="visible";) Javascript in my addtable function to display the table but it does not work. I am not sure if I am understanding this right.
Also how do I control the display of the table (like width, background color, font etc). I added (td.style.width = '200px'; but I don't see any changes).
CSS or JS for controlling table ?
function addTable() {
var table = document.createElement('TABLE').style.display = "block";
table.border='0';
for (var i=0; i<3; i++){
var tr = document.createElement('tr');
for (var j=0; j<4; j++){
var td = document.createElement('td');
td.style.width = '200px';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
}
function addRow() {
var myName = document.getElementById("name");
var domainName = document.getElementById("domain");
var url = document.getElementById("url");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(0).innerHTML= myName.value;
row.insertCell(1).innerHTML= domainName.value;
row.insertCell(2).innerHTML= url.value;
}
function load() {
console.log("Check if this loads");
}
/*
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
*/
#myTableData {visibility: hidden;}
body {
background: gray;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="table-app.js"></script>
<link rel="stylesheet" href="table-app.css">
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Domain</td>
<td><input type="text" id="domain">
</td>
</tr>
<tr>
<td>URL</td>
<td><input type="text" id="url"></td>
</tr>
<tr>
<td colspan=2><input type="button" id="add" value="Display as Table" onclick="Javascript:addRow()"></td>
</tr>
</table>
</div>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<th>Name</td>
<th>Domain</th>
<th>URL</th>
</tr>
</table>
</div>
<!--
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript
</div> -->
</body>
</html>
1) In function addRow add table.style.visibility = "visible"; ,to display the table, right after var table = document.getElementById("myTableData");.
2) To set styles like width you can can use setAttribute method.
document.getElementById('myTableData').setAttribute("style","width:200px");
Note: I can't see where you make use of addTable function, maybe this is why some of styles are not setted when you want.
function addTable() {
var table = document.createElement('TABLE').style.display = "block";
table.border='0';
for (var i=0; i<3; i++){
var tr = document.createElement('tr');
for (var j=0; j<4; j++){
var td = document.createElement('td');
td.style.width = '200px';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
}
function addRow() {
var myName = document.getElementById("name");
var domainName = document.getElementById("domain");
var url = document.getElementById("url");
var table = document.getElementById("myTableData");
table.style.visibility = "visible";
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
//row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(0).innerHTML= myName.value;
row.insertCell(1).innerHTML= domainName.value;
row.insertCell(2).innerHTML= url.value;
}
function load() {
console.log("Check if this loads");
}
/*
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
*/
#myTableData {visibility: hidden;}
body {
background: gray;
}
<!DOCTYPE html>
<html>
<head>
<title>HTML dynamic table using JavaScript</title>
<script type="text/javascript" src="table-app.js"></script>
<link rel="stylesheet" href="table-app.css">
</head>
<body onload="load()">
<div id="myform">
<b>Simple form with name and age ...</b>
<table>
<tr>
<td>Name</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Domain</td>
<td><input type="text" id="domain">
</td>
</tr>
<tr>
<td>URL</td>
<td><input type="text" id="url"></td>
</tr>
<tr>
<td colspan=2><input type="button" id="add" value="Display as Table" onclick="Javascript:addRow()"></td>
</tr>
</table>
</div>
<table id="myTableData" border="1" cellpadding="2">
<tr>
<th>Name</td>
<th>Domain</th>
<th>URL</th>
</tr>
</table>
</div>
<!--
<div id="myDynamicTable">
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
to create a Table and add some data using JavaScript
</div> -->
</body>
</html>
I don't have the rep to comment so I can't ask for details, but just in case you can use jquery, you can hide and show stuff like this:
$(function(){
$("#add").click(function() {
var name = $('#name').val();
var domain = $('#domain').val();
var url = $('#url').val();
$('#hidey').show();
$('#nametd').html(name);
$('#domtd').html(domain);
$('#urltd').html(url);
})
});
https://jsfiddle.net/6dxLsnL4/
Or trigger on form submit instead of click if you want, but there, you might want to consider ajax, because then you can make sure the form is processed on the server side before displaying the results.

Add data to a html table in Javascript

I have the following problem. I would like to add some data to a table using label values (in this case 7 & 5) but every time I try to add a value, the cells show the message "undefined". The main idea is to create a table which values are going to be used to draw a bar chart (graph) using the highcharts library
<h2>Add Row in JavaScript</h2>
<table id="table" cellspacing="0" border="1">
<tbody>
<tr>
<td>Name</td>
<td>Address</td>
</tr>
</tbody>
</table>
<button onclick="javascript:addRow('table')">Add row</button>
<br></br>
<label id="txt1" value="7" text="a">label 1</label>
<label id="txt2" value="5" text="b">label 2</label>
Script:
function addRow(id){
var label = ($("#txt1").val());
var label2 = ($("#txt2").val());
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
var data1 = document.createElement("td");
data1.appendChild(document.createTextNode(label.value));
var data2 = document.createElement("td");
data2.appendChild(document.createTextNode(label2.value));
row.appendChild(data1);
row.appendChild(data2);
tbody.appendChild(row);
}
Example in JFiddle
Code
Highcharts library
Code
It seems you have taken label instead of textbox, anyway below is working code.
function addRow(id) {
var label = ($("#txt1").attr("value"));
var label2 = ($("#txt2").attr("value"));
var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
var row = document.createElement("tr");
var data1 = document.createElement("td");
data1.appendChild(document.createTextNode(label));
var data2 = document.createElement("td");
data2.appendChild(document.createTextNode(label2));
row.appendChild(data1);
row.appendChild(data2);
tbody.appendChild(row);
}

How to insert a row in an HTML table body in JavaScript

I have an HTML table with a header and a footer:
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
<tfoot>
</table>
I am trying to add a row in tbody with the following:
myTable.insertRow(myTable.rows.length - 1);
but the row is added in the tfoot section.
How do I insert tbody?
If you want to add a row into the tbody, get a reference to it and call its insertRow method.
var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var newCell = newRow.insertCell();
// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>initial row</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My Footer</td>
</tr>
</tfoot>
</table>
(old demo on JSFiddle)
You can try the following snippet using jQuery:
$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
Basic approach:
This should add HTML-formatted content and show the newly added row.
var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
I think this script is what exactly you need
var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)
You're close. Just add the row to the tbody instead of table:
myTbody.insertRow();
Just get a reference to tBody (myTbody) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.
A live demo is at jsFiddle.
Add rows:
<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>
And cells.
let myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];
let row = myTable.insertRow();
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);
cell1.innerHTML = 1;
cell2.innerHTML = 'JAHID';
cell3.innerHTML = 23;
row = myTable.insertRow();
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell1.innerHTML = 2;
cell2.innerHTML = 'HOSSAIIN';
cell3.innerHTML = 50;
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #000;
padding: 10px;
}
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
</tr>
</thead>
<tbody></tbody>
</table>
Add Column, Add Row, Delete Column, Delete Row. Simplest way
function addColumn(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
for(i=0;i<row.length;i++){
row[i].innerHTML = row[i].innerHTML + '<td></td>';
}
}
function deleterow(tblId)
{
var table = document.getElementById(tblId);
var row = table.getElementsByTagName('tr');
if(row.length!='1'){
row[row.length - 1].outerHTML='';
}
}
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
function myFunction(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].outerHTML;
table.innerHTML = table.innerHTML + row;
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].getElementsByTagName('td');
for(i=0;i<row.length;i++){
row[i].innerHTML = '';
}
}
table, td {
border: 1px solid black;
border-collapse:collapse;
}
td {
cursor:text;
padding:10px;
}
td:empty:after{
content:"Type here...";
color:#cccccc;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<p>
<input type="button" value="+Column" onclick="addColumn('tblSample')">
<input type="button" value="-Column" onclick="deleteColumn('tblSample')">
<input type="button" value="+Row" onclick="myFunction('tblSample')">
<input type="button" value="-Row" onclick="deleterow('tblSample')">
</p>
<table id="tblSample" contenteditable><tr><td></td></tr></table>
</form>
</body>
</html>
You can also use querySelector to select the tbody, then insert a new row at the end of it.
Use append to insert Node or DOMString objects to a new cell, which will then be inserted into the new row.
var myTbody = document.querySelector("#myTable>tbody");
var newRow = myTbody.insertRow();
newRow.insertCell().append("New data");
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
I have tried this, and this is working for me:
var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);
You can use the following example:
<table id="purches">
<thead>
<tr>
<th>ID</th>
<th>Transaction Date</th>
<th>Category</th>
<th>Transaction Amount</th>
<th>Offer</th>
</tr>
</thead>
<!-- <tr th:each="person: ${list}" >
<td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
</tr>
-->
<tbody id="feedback">
</tbody>
</table>
JavaScript file:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
// var json = "<h4>Ajax Response</h4><pre>" + JSON.stringify(data, null, 4) + "</pre>";
// $('#feedback').html(json);
//
console.log("SUCCESS: ", data);
//$("#btn-search").prop("disabled", false);
for (var i = 0; i < data.length; i++) {
//$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
$('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');
alert(data[i].accountNumber)
}
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR: ", e);
$("#btn-search").prop("disabled", false);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<div id="myDiv">
<label for="name">Name:</label>
<input
type="text"
name="myInput"
id="myInput"
placeholder="Name of expense"
size="50"
/><br /><br />
<label for="date">Date:</label>
<input type="date" id="myDate" name="myDate" />
<label for="amount">Amount:</label>
<input
type="text"
name="myAmount"
id="myAmount"
placeholder="Dollar amount ($)"
/><br /><br />
<span onclick="addRow()" class="addBtn">Add Expense</span>
</div>
<br />
<input type="button" value="Add Rows" onclick="addRows()" />
<!-- Optional position -->
<table id="myTable">
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Delete</th>
</tr>
<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>
</table>
<script>
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
function addRows() {
console.log("add rows");
document.getElementById("myTable").innerHTML += `<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>`;
}
</script>
</body>
</html>
$("#myTable tbody").append(tablerow);

how to remove and re-order cells in a table in JavaScript

As per question how could I remove empty cells and bring cells with data on top of the table in JavaScript/Prototype, basically all cells with data will be at the top and then empty cells should be removed.
<table>
<tr class="row">
<td class="c1">Cell1</td>
<td class="c2">Cell2</td>
</tr>
<tr class="row">
<td class="c1">Cell1</td>
<td class="c2"></td>
<td class="c3">Cell3</td>
</tr>
<tr class="row">
<td class="c1">Cell1</td>
<td class="c2">Cell2</td>
<td class="c3"></td>
</tr>
</table>
Cell1 Cell2 Cell1 Cell2 Cell3
Cell1 Cell3 ---> Cell1 Cell2
Cell1 Cell2 Cell1
Thanks
In the end it's a little bit of an algorithm that needs to be coded.
I simply used DOM-functionality as I'm not that familiar with jQuery or other frameworks, but I think you can figure out the idea of the algorithm. It shouldn't be too hard to convert it.
<html>
<head>
<script type="text/javascript">
function init() {
var table = document.getElementsByTagName("table")[0];
var trs = table.getElementsByTagName("tr");
var data = [];
var rows, columns;
// run through all TRs and TDs and collect the data into an array without
// empty slots
for (var r = 0; r < trs.length; r++) {
var tds = trs[r].getElementsByTagName("td");
for (var d = 0; d < tds.length; d++) {
if (tds[d].innerHTML) {
data[d] = (data[d] || []).concat(tds[d].innerHTML);
}
}
}
// the tricky thing now is to convert the X/Y alignment of the
// elements in data into a Y/X one for the table
columns = data.length; // target table will have this many columns
rows = data[0].length; // target table will have this many rows
table = document.createElement("table");
for (var r = 0; r < rows; r++) {
var tr = document.createElement("tr");
for (var c = 0; c < columns; c++) {
var td = document.createElement("td");
td.innerHTML = data[c][r] || "";
tr.appendChild(td);
}
table.appendChild(tr);
}
document.body.appendChild(table);
}
</script>
</head>
<body onload="init()">
<table>
<tr class="row">
<td class="c1">Cell1</td>
<td class="c2">Cell2</td>
</tr>
<tr class="row">
<td class="c1">Cell1</td>
<td class="c2"></td>
<td class="c3">Cell3</td>
</tr>
<tr class="row">
<td class="c1">Cell1</td>
<td class="c2">Cell2</td>
<td class="c3"></td>
</tr>
</table>
</body>
</html>
The output matches your request.
window.onload = function() {
var tds = document.getElementsByTagName("td");
for(var i=0; i<tds.length; i++) {
if(tds[i].innerHTML == "") {
tds[i].parentNode.removeChild(tds[i]);
}
}
};

Categories