table row as a counter in HTML - javascript

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>

Related

how to show table cell using js

description cells will starts as hide. The row that I click, will show the description and if i click another row will the current row description and hide the other description
var getTable = document.querySelector("tbody");
var cells = getTable.getElementsByTagName("td");
for (let item of document.getElementsByClassName("desc")) {
item.style.display = "none";
}
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function () {
var selectedRow =
getTable.getElementsByTagName("tr")[this.parentNode.rowIndex];
if (!this.parentNode.rowIndex) {
$(selectedRow).find(".desc").css("display", "none");
} else {
$(selectedRow).find(".desc").css("display", "block");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblInventory">
<thead>
<tr>
<th>UPC</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>987456</td>
<td>Product Blanks</td>
<td class="desc">Unfinished template for parts 1000222 to 1000299</td>
</tr>
<tr>
<td>654123</td>
<td>Threaded Rods</td>
<td class="desc">Rods threaded at both ends for Support Brackets</td>
</tr>
</tbody>
</table>
Try this in vanilla:
document.querySelector('#tblInventory').addEventListener('click', (e) =>
{
// Hide other descriptions
document.querySelectorAll('#tblInventory td.desc span').forEach(span => {
span.style.display = 'none';
});
// Show clicked row description
if (e.target.tagName === 'TD') {
e.target.parentNode.querySelector('td.desc span').style.display = 'inline';
}
});
#tblInventory td.desc span {
display: none
}
<table id="tblInventory">
<thead>
<tr>
<th>UPC</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>987456</td>
<td>Product Blanks</td>
<td class="desc"><span>Unfinished template for parts 1000222 to 1000299</span></td>
</tr>
<tr>
<td>654123</td>
<td>Threaded Rods</td>
<td class="desc"><span>Rods threaded at both ends for Support Brackets</span></td>
</tr>
</tbody>
</table>
Or with jQuery:
$('#tblInventory').on('click', 'td', (e) => {
// Hide other descriptions
$('#tblInventory td.desc span').hide();
// Show clicked row description
$(e.target).closest('tr').find('td.desc span').show();
});
#tblInventory td.desc span {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<table id="tblInventory">
<thead>
<tr>
<th>UPC</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>987456</td>
<td>Product Blanks</td>
<td class="desc"><span>Unfinished template for parts 1000222 to 1000299</span></td>
</tr>
<tr>
<td>654123</td>
<td>Threaded Rods</td>
<td class="desc"><span>Rods threaded at both ends for Support Brackets</span></td>
</tr>
</tbody>
</table>
Using span is a suggestion, but you can fix the selectors to show/hide the td elements directly as well;
If you don't want to hide previous clicked descriptions, just remove the related code.

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.

How to get all the elements of a column from html table and validate if a particular string exists in that list

I have a html table with multiple rows and columns. I want to pull all the values by column id and compare with some matching string. If matches i want to enable a button on the page.
Could you please let me know how to refer the column by id in $(document).ready function.
Here is the table
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<th:block th:each="it : ${data}">
<tr>
<td th:text="${it.id}">id</td>
<td th:text="${it.name}">name</td>
<td th:text="${it.place}">place</td>
</tr>
</th:block>
</table>
Button:
style="visibility:hidden">Submit
$(document).ready(function(){
//here i want to pull the place column and verify if one of the
places matches my input string enable submit button
$("#submitbutton").css("visibility", "visible");
}
}
This function will take all information inside you td and search for the string you looking for :
But i cannot get the point that you search for a particular string instead of searching for an object.
const addresses = [...document.querySelectorAll(".address")];
const serchFromList = (arr, str) => {
return arr.map(el =>
el = el.innerHTML
).filter(el => el === str)
}
console.log(serchFromList(addresses, "NY"))
/* in case you want a boolean you can use some*/
const isAddressExist = (arr, str) => {
return arr.map(el =>
el = el.innerHTML
).some(el => el === str)
}
console.log(isAddressExist(addresses, "NY"))
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<th>
<tr>
<td>4545</td>
<td>5454</td>
<td>65687</td>
</tr>
<tr>
<td>aziz</td>
<td>david</td>
<td>paul</td>
</tr>
<tr>
<td class='address'>NY</td>
<td class='address'>MTL</td>
<td class='address'>BC</td>
</tr>
</th>
</table>
Should be pretty doable with XPath if you don't want to add extra attributes to Place cell. Just find out the position of Place column and get the text from the same position of <td>.
// Get the table node first
let node = document.getElementById('data')
// Find out position of `Place` column
let nth = document.evaluate('count(//th[text()="Place"]/preceding-sibling::*)+1', node).numberValue
// Get all the place cell by the position
let placeCells = document.evaluate(`//td[position()=${nth}]`, node)
// Get all the place names
let places = [],
placeNode = placeCells.iterateNext()
while (placeNode) {
places.push(placeNode.textContent)
placeNode = placeCells.iterateNext()
}
console.log(places)
// ['NYC', 'SF', 'LA']
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<tbody>
<tr>
<td>0001</td>
<td>Mary</td>
<td>NYC</td>
</tr>
<tr>
<td>0002</td>
<td>John</td>
<td>SF</td>
</tr>
<tr>
<td>0003</td>
<td>Bob</td>
<td>LA</td>
</tr>
</tbody>
</table>

Get all rows from dynamical table jQuery

I am trying to read all rows from a dynamic table. The main idea is to read all the rows and store it in an array for further processing. But so far I have not been able to get the row data. The code below only returns the table headers.
Here is the code:
var data = [];
var i = 0;
$('#tempTable td').each(function (index, tr) {
var tds = $(tr).find('td');
if (tds.length > 1) {
data[i++] = {
action: tds[0].textContent,
spec: tds[1].textContent,
data: tds[2].textContent,
unit: tds[3].textContent,
upper_tol: tds[4].textContent,
lower_tol: tds[5].textContent,
tol_unit: tds[6].textContent,
def: tds[7].textContent
}
}
});
And the HTML markup looks like this:
<table id='tempTable'>
<thead>
<tr>
<td class='table_head' width='80px'>Header1</td>
<td class='table_head' width='435px'>Header2</td>
<td class='table_head' width='100px'>Header3</td>
<td class='table_head' width='100px'>Header4</td>
<td class='table_head' width='100px'>Header5</td>
<td class='table_head' width='100px'>Header6</td>
<td class='table_head' width='100px'>Header7</td>
<td class='table_head' width='80px'>Header8</td>
</tr>
</thead>
<tbody>
<!-- Rows inserted dynamically here using jQuery -->
</tbody>
</table>
You have initialized your table headers as 'td' instead you need to initialize them in 'th' as below..
<table id='tempTable'>
<thead>
<tr>
<th class='table_head' width='80px'>Header1</th>
<th class='table_head' width='435px'>Header2</th>
<th class='table_head' width='100px'>Header3</th>
<th class='table_head' width='100px'>Header4</th>
<th class='table_head' width='100px'>Header5</th>
<th class='table_head' width='100px'>Header6</th>
<th class='table_head' width='100px'>Header7</th>
<th class='table_head' width='80px'>Header8</th>
</tr>
</thead>
<tbody>
<!-- Rows inserted dynamically here using jQuery -->
</tbody>
</table>
Also see the at which event you are selecting table data(Before selection table should be filled with data).
For selecting the data from table :
//traverse each row
$('#tempTable tr').each(function (index, tr) {
var cols = [];
//get td of each row and insert it into cols array
$(this).find('td').each(function (colIndex, c) {
cols.push(c.textContent);
});
//insert this cols(full rows data) array into tableData array
tableData.push(cols);
});
console.log("tableData: ", tableData);
Please find the fiddle https://jsfiddle.net/Prakash_Thete/frm2ebug/1/ for the same..

jquery dynamic table id thead th selection

I'm new to jquery. May be my query looks some what dumb, but really I'm not understanding how to achieve below thing.
Anyway, here is my query:
I have some dynamic tables as below:
<table id='example1'>
<thead>
<tr>
<th>one</th>
<th>two</th>
<th>three</th>
</tr>
</thead>
</table>
<table id='example2'>
<thead>
<tr>
<th>one</th>
<th>two</th>
<th>three</th>
</tr>
</thead>
</table>
I am trying as below:
$($('table').attr('id') ' thead th').each( function () {
}
Seems something wrong above, could anyone please correct?
I need to achieve as below:
$( dynamicTableId thead th).each(function () {
}
There is no need to have the if you are trying to iterate over all the th elements, Just use the table as selector. You can also use an has attribute selector to make sure it has an id
$('table[id] thead th').each( function () {
})
I Guess i have done in my project , here it is:
<script type="text/javascript">
for (var t=1; t < 4; t++) // Number of table
{
document.write("<table border='1' id='example"+t+"'>");
for (var a=1; a < 5; a++) // Number of row for table
{
document.write("<tr>");
for(var b=1; b<4; b++) // Number of column for table
{
document.write("<td>Table "+t +" " + b+"</td>");
}
document.write("</tr>");
}
document.write("</table>");
document.write("<br/><br/><br/>");
}
</script>
There are better ways to do this, though!
$('.example thead th').each(function () { 
console.log($(this).text());
});
<table id='example1' class="example">
<thead>
<tr>
<th>one</th>
<th>two</th>
<th>three</th>
</tr>
</thead>
</table>
<table id='example2' class="example">
<thead>
<tr>
<th>one</th>
<th>two</th>
<th>three</th>
</tr>
</thead>
</table>

Categories