Remove empty rows and move content from table to other row - javascript

I have table:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<table class="table-bordered" width="100%">
<tr>
<th>Product</th>
<th>Service</th>
</tr>
<tr>
<td>Product 1</td>
<td>S11</td>
</tr>
<tr>
<td></td>
<td>S13</td>
</tr>
<tr>
<td></td>
<td>S14</td>
</tr>
<tr>
<td>Product 2</td>
<td>S11</td>
</tr>
<tr>
<td></td>
<td>S120</td>
</tr>
</table>
I need: where empty row with product (where product's name is empty) delete this row and move service to up product row and delete current service from up product. Example:
In this table we have product 1. I need remove S11 and paste: S13 and S14 in single row.
I need this table on result:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<table class="table-bordered" width="100%">
<tr>
<th>Product</th>
<th>Service</th>
</tr>
<tr>
<td>Product 1</td>
<td>S13, S14</td>
</tr>
<tr>
<td>Product 2</td>
<td>S120</td>
</tr>
</table>
I think, that this we can do with javascript or jquery. I try write this code:
$('table tr').each(function () {
if (!$.trim($(this).text())) $(this).remove();
});
But this only remove empty rows..

let tr
$('table tr').each(function () {
if($(this).find('td:nth-child(1)').text().length){
tr = $(this)
tr.find('td:nth-child(2)').text('')
}else{
let td = $(tr).find('td:nth-child(2)')
td.text(td.text() + ' ' + $(this).find('td:nth-child(2)').text())
$(this).remove()
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<table class="table-bordered" width="100%">
<tr>
<th>Product</th>
<th>Service</th>
</tr>
<tr>
<td>Product 1</td>
<td>S11</td>
</tr>
<tr>
<td></td>
<td>S13</td>
</tr>
<tr>
<td></td>
<td>S14</td>
</tr>
<tr>
<td>Product 2</td>
<td>S11</td>
</tr>
<tr>
<td></td>
<td>S120</td>
</tr>
</table>

for (var x= 0; x < $("table.table-bordered").children[0].children.length; x++) // loop through all table rows.
{
if($("table.table-bordered").children[0].children[x].children[1].outerHTML.indexOf(',') != -1) // if the second td of the table contains a comma
{
var arr = $("table.table-bordered").children[0].children[x].children[1].innerHTML.split(','); // split the array so you make as many rows as needed
for (var y = 1; y < arr.length; y++) { // loop trough the array
var row = document.createElement('tr'); // create a new row
var first = document.createElement('td');
row.append(first) // create a empty td and add it to the row
var second = document.createElement('td'); // create another td
second.append(arr[y]); // append the value (whats after the comma)
row.append(second); // add it to the row
$("table.table-bordered > tbody").append(row); // add the row to the table
}
};
}
With this i managed to add a row to the table but i didn't have time to add it in the right place but you could look into that yourself.
I hope this helps, but to be honest I think you would be better of changing it in the backend.

Related

Group column with the same subheader name in datatable using Javascript/jQuery

I have a table like this
In which I have different city where we have demand-supply of different products.
Now what I want as here demand is different for all the products However supply is the same on all of three product, so I want that table looks like in this manner.
What I want to do is I want only to show the supply column once in the last of the table. This has to be done dynamically as in the future we have multiple products
Can anyone help me with this?
What the code below does is:
Identify the positions of the "Supply"'s and store them in ind array, in this case will be [3, 5, 7]
Loops through ind except for the last element 7(as one "Supply" will be left) and hide all td's; $("td:nth-child("3"), $("td:nth-child("5")
The "Demand"s that precede each of these elements will be assigned two spaces.
let ind = [];
$("td:contains('Supply')").each(function (index) {
ind.push($(this).index() + 1);
});
$(".hide").on("click", function () {
for (let i = 0; i < ind.length - 1; i++) {
let el = $("td:nth-child(" + ind[i] + ")");
el.prev().attr("colspan", "2");
el.hide();
}
});
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th>City</th>
<th colspan="2">Product 1</th>
<th colspan="2">Product 2</th>
<th colspan="2">Product 3</th>
</tr>
<tr>
<td></td>
<td>Demand</td>
<td>Supply</td>
<td>Demand</td>
<td>Supply</td>
<td>Demand</td>
<td>Supply</td>
</tr>
<tr>
<td>City 1</td>
<td>50$</td>
<td>60$</td>
<td>90$</td>
<td>60$</td>
<td>100$</td>
<td>60$</td>
</tr>
<tr>
<td>City 2</td>
<td>50$</td>
<td>60$</td>
<td>90$</td>
<td>60$</td>
<td>100$</td>
<td>60$</td>
</tr>
<tr>
<td>City 3</td>
<td>50$</td>
<td>60$</td>
<td>90$</td>
<td>60$</td>
<td>100$</td>
<td>60$</td>
</tr>
<tr>
<td>City 4</td>
<td>50$</td>
<td>60$</td>
<td>90$</td>
<td>60$</td>
<td>100$</td>
<td>60$</td>
</tr>
</table>
<button class="hide">Hide</button>

Hide empty html table rows

Problem
I have a table with one or more empty rows. How to hide empty rows from the table?
For example
1 - John | Alfredo
2 - Mark | Zuck
3 - |
4 - Carl | Johnson
In this case, I'd like to delete the third row.
Step Tried
I found how to delete a specific row, what about deleting all the empty rows?
deleteEmptyRows();
function deleteEmptyRows() {
var myTable = document.getElementById("myTable")
var rowToDelete = 2;
myTable.deleteRow(rowToDelete)
}
<table border="1" cellspacing="1" cellpadding="1" id ="myTable">
<tbody>
<tr>
<td>John</td>
<td>Alfredo</td>
</tr>
<tr>
<td>Mark</td>
<td>Zuck</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>Carl</td>
<td>Johnson</td>
</tr>
</tbody>
</table>
This is how you can dynamically hide empty table rows with javascript.
deleteEmptyRows();
function checkIfCellsAreEmpty(row) {
var cells = row.cells;
var isCellEmpty = false;
for(var j = 0; j < cells.length; j++) {
if(cells[j].innerHTML !== '') {
return isCellEmpty;
}
}
return !isCellEmpty;
}
function deleteEmptyRows() {
var myTable = document.getElementById("myTable");
for(var i = 0; i < myTable.rows.length; i++) {
var isRowEmpty = checkIfCellsAreEmpty(myTable.rows[i]);
if (isRowEmpty) {
myTable.rows[i].style.display = "none";
}
}
}
<table border="1" cellspacing="1" cellpadding="1" id ="myTable">
<tbody>
<tr>
<td>John</td>
<td>Alfredo</td>
</tr>
<tr>
<td>Mark</td>
<td>Zuck</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>Carl</td>
<td>Johnson</td>
</tr>
</tbody>
</table>
Here, a simple method for row is empty (this allows us to check for other conditions easily later).
Loop over rows and call remove if empty.
const rowIsEmpty = (tr) => Array.from(tr.querySelectorAll('td')).every(td => td.innerText === "");
deleteEmptyRows();
function deleteEmptyRows() {
var myTable = document.getElementById("myTable");
myTable.querySelectorAll('tr').forEach(tr => {
if(rowIsEmpty(tr)) tr.remove();
});
}
<table border="1" cellspacing="1" cellpadding="1" id ="myTable">
<tbody>
<tr>
<td>John</td>
<td>Alfredo</td>
</tr>
<tr>
<td>Mark</td>
<td>Zuck</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>Carl</td>
<td>Johnson</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Was answered in another thread.
Jquery: hiding empty table rows
Loops through all table tr rows, and checks td lengths. If the td length is empty will hide.
$("table tr").each(function() {
let cell = $.trim($(this).find('td').text());
if (cell.length == 0){
console.log('Empty cell');
$(this).addClass('nodisplay');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
</tr>
<tr>
<!-- Will hide --> <td></td>
</tr>
</table>
With native Javascript:
function removeRow(src) {
var tableRows = document.getElementById(src).querySelectorAll('tr');
tableRows.forEach(function(row){
if((/^\s*$/).test(row.innerText)){
row.parentNode.removeChild(row);
}
});
}
removeRow('myTable');
The only problem is when you have some other characters in the row, except the whitespaces. This regex checks for blank characters, but if u have a dot inside or any other non empty character, it will fail.

universal javascript selector to interact on all html element

I started on that http://jsfiddle.net/DRFBG/
And if I add tables so mytable1, mytable2,...
<table id="mytable1" border="1">
<tr><th>Column1</th><th>Column2</th><th>Column3</th><th>Column4</th></tr>
<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>
</table>
<table id="mytable2" border="1">
<tr><th>Column1</th><th>Column2</th><th>Column3</th><th>Column4</th></tr>
<tr class="data"><td>1st</td><td>1.1</td><td>1</td><td></td></tr>
<tr class="data"><td>2nd</td><td>2.01</td><td>2</td><td></td></tr>
<tr class="data"><td>3rd</td><td>3.001</td><td>3</td><td></td></tr>
<tr class="data"><td>4th</td><td>4.01</td><td>4</td><td></td></tr>
</table>
How could I uniform my javascript code for all tables?
I've already tried passing by table[div^=mytable]*, but the problem is the second selector in the function.
So any ideas please? Thank you? Sorry for my english
By the way, the code is to remove th with empty td for each table
$('#mytable2 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 == ($('#mytable2 tr').length - 1)) {
$(this).hide();
tds.hide();
}
});
One approach is, selecting tables first and get their id and after that, doing the approach of http://jsfiddle.net/DRFBG/ on each of them like the following:
$('table').each(function()
{
var tb_id = $(this).attr('id');
$('#'+tb_id+' 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 == ($('#'+tb_id+' tr').length - 1)) {
$(this).hide();
tds.hide();
}
});
});
Here is the working jsfiddle
To select all on your page you can use "table" selector.
So you'd need to use $('table2 th') instead of $('#mytable2 th')
One possible solution would be to loop through each column of each table, then check if there are any non-empty cells. If there is not, then you can safely remove() all the td and th within that column.
Note that the removal needs to be done last, otherwise it will affect the indexing of the following columns. You can do that by simply marking the cells to be removed with a class, and then selecting that class once all loops complete. Try this:
$('table').each(function() {
var $table = $(this);
var rows = $table.find('tr').length - 1; // -1 to account for the headings
$table.find('th').each(function(i, th) {
var $empty = $table.find(`td:nth-child(${i + 1}):empty`);
if ($empty.length == rows)
$empty.add(this).addClass('to-remove');
})
$table.find('.to-remove').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="mytable1" border="1">
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
</tr>
<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>
</table>
<table id="mytable2" border="1">
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Column4</th>
</tr>
<tr class="data">
<td>1st</td>
<td>1.1</td>
<td>1</td>
<td></td>
</tr>
<tr class="data">
<td>2nd</td>
<td>2.01</td>
<td>2</td>
<td></td>
</tr>
<tr class="data">
<td>3rd</td>
<td>3.001</td>
<td>3</td>
<td></td>
</tr>
<tr class="data">
<td>4th</td>
<td>4.01</td>
<td>4</td>
<td></td>
</tr>
</table>

table row as a counter in HTML

I would like to know how could I assign a table row an id which is systematically as a counter. It can be a string + a counter as follow:
<table>
<tr id="Row1"> # it can be only a number => id="1"
<tr id="Row2"> # it can be only a number => id="2"
<tr id="Row3"> # it can be only a number => id="3"
.....
<tr id="Row5000"> # it can be only a number => id="5000"
</table
Because I have thousands of rows and then could not assign id to them manually. This is why I want to assign them via XSLT. Does anybody know how could I do so? Thanks.
// javascript
var table = document.querySelectorAll('table tr');
{
for(var i=0;i<table.length;i++){
table[i].setAttribute("id",i+1);
}
//jquery
$("table tr").each(function(index,object) {
object.attr("id",(index+1));
})
$("table tr").each(function(i, tr) {tr.id = 'Row' + (i+1);})
explanation: you can find each tr in table and assign id for each one.
First you assign an id attribute to your table like this
<table id="mytable">
<tr></tr>
<tr></tr>
....
</table>
Then add a script at the bottom of your document
<script>
(function() {
var rows = document.getElementById("mytable").rows;
for(var i = 1; i <= rows.length; i++) {
rows[i-1].id = 'Row'+i;
}
})();
Its a pure javascript solution. No jQuery required.
Assign your table an id. here its newTable then iterate and set the attibute
<script>
function getit(){
$('#newTable').find('tr').each(function(index){
var x= this.setAttribute("id","Row"+[index]);
console.log(x);
})
}
</script>
hope that helped.
You Can Use This:
Your CSS
<style>
body {
counter-reset: section;
}
table tbody tr th::before {
counter-increment: section;
content: "Section " counter(section);
}
table tbody tr th::before {
content: counter(section);
}
</style>
Your Html
<table class="table">
<thead>
<tr>
<th colspan="6">
</th>
</tr>
<tr>
<th scope="col">#</th>
<th scope="col">f1</th>
<th scope="col">f2</th>
<th scope="col">f3</th>
<th scope="col">f4</th>
<th scope="col">f5</th>
</tr>
</thead>
<tbody>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
</tbody>
</table>

Hide rows in table B which already appear in table A

Using this code :
var table1 = $('#TableA').find('td:eq(1)').text();
var table2 = $("#TableB tr:gt(0)");
table2.each(function (i) {
var tds = $(this).children('td');
var type= +tds.eq(0).text();
var price = +tds.eq(1).text();
if (price == table1) {
var myTable = table2.filter(function () {
var tds = $(this).children('td');
})
myTable.add(this).hide()
}
})
My Html Page Structure
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table id="TableA">
<tr>
<th>Type</th>
<th>Price</th>
<th>Quantity</th>
<th>Ref No</th>
</tr>
<tr>
<td>Mouse</td>
<td>50</td>
<td>6</td>
<td>#101255</td>
</tr>
<tr>
<td>Speaker</td>
<td>300</td>
<td>6</td>
<td>#21165</td>
</tr>
</table>
<table id="TableB">
<tr>
<th>Type</th>
<th>Price</th>
<th>Quantity</th>
<th>Ref No</th>
</tr>
<tr>
<td>Mouse</td>
<td>50</td>
<td>6</td>
<td>#101255</td>
</tr>
<tr>
<td>Speaker</td>
<td>300</td>
<td>6</td>
<td>#21165</td>
</tr>
<tr>
<td>Keyboard</td>
<td>150</td>
<td>7</td>
<td>#31234</td>
</tr>
</table>
</body>
</html>
"The second table in the images is the Table B"
My Table B changes from this :
Before
To this : After
Now my problem is, only one row is hidden. The row, where "speaker" is, is still displayed. I know that I must use a loop for this, but I don't where to implement the loop and how. I'm a newbie programmer and I know that I need more practice. Please Help Thank you in advance
<script type="text/javascript">
$('body').click(function(e){
var table1_tr = $('#TableA').find('tr'); <!--get the rows of first table-->
var table2 = $("#TableB tr:gt(0)");
table1_tr.each(function(i,e){ <!-- loop through rows of first table -->
var table1 = $(e).find('td:eq(1)').text();
table2.each(function (i) {
var tds = $(this).children('td');
var type= +tds.eq(0).text();
var price = +tds.eq(1).text();
if (price == table1) {
var myTable = table2.filter(function () {
var tds = $(this).children('td');
})
myTable.add(this).hide()
}
});
})
});
</script>
you are checking the text of price in the first row of first table with td text of all the rows of second table
I modified script to loop through rows of first table and check them with all rows of second table
Hope this helps

Categories