How to obtain row and column information of a clicked table - javascript

I have the following fiddle - where I am testing out a concept of getting to the data in a table. At the moment, I can get to the value displayed in a particular cell, when i click on the cell.
In addition, I would like to be able to get the row and column index of the clicked cell. Does anyone here know how to do this?
Link to fiddle
var tbl = document.getElementById("recordingTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
<table cellspacing="1" id="recordingTable">
<!-- this is the head element -->
<thead class="callView">
<!--specify the columns -->
<tr>
<th>STATE</th>
<th>CALLID</th>
<th>COLLECTED</th>
<th>ZONE</th>
</tr>
</thead>
<!-- -->
<tbody class="callView">
<tr>
<td>0</td>
<td>10001</td>
<td>1</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>10002</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>0</td>
<td>10003</td>
<td>spring</td>
<td>1</td>
</tr>
</tbody>
</table>

Insead of adding onclick event to each cell you can add it to table, and get neccesary info from argument:
var tbl = document.getElementById("recordingTable");
tbl.onclick = function(e)
{
console.log(e.target.innerHTML);
console.log(e.target.cellIndex);
console.log(e.target.parentElement.rowIndex);
}
JsFiddle: https://jsfiddle.net/19qfsxr9/14/

You can get by using
cel.rowIndex
cel.cellIndex
in the function

Related

how to select a range of html table cell value in javascript?

Please help!
I have a html table and for example I want to select the first 4 cell value of the table but I don't know how.
I tried:
var table = document.getElementById("td")
selectedCell = table.cells[0:4]
javascript does not understand this way.
You can access a cell by its row index and cell index like this:
var table = document.getElementById('table1')
for(let rowIndex = 0; rowIndex < 2; rowIndex++){
for(let cellIndex = 0; cellIndex < 2; cellIndex++){
console.log(table.rows[rowIndex].cells[cellIndex]);
}
}
<table id="table1" style="width:100%">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
<tr>
<td>March</td>
<td>$70</td>
</tr>
<tr>
<td>April</td>
<td>$160</td>
</tr>
</table>
if you give some sample data and an expected output I can use it to help you to make adjustment to this.

Continue loop through all tbody element and add id to all tr's

I have many tables and I want to give all tr's individual ids. I loop through all tbody but it only affects first tbody, not all of them. When I add loop indicating each tbody they work. Is there any efficient way available to loop through all tbody and give the tr's individual id. I want to do it using vanilla javascript, no jQuery.
My sample code here :
<table><tbody>
<tr><td>No.</td><td>Name</td><td>Score</td></tr>
<tr><td>01</td><td>ted</td><td>0.50</td></tr>
<tr><td>02</td><td>joe</td><td>0.25</td></tr>
</tbody></table>
<table><tbody>
<tr><td>Name</td><td>Address</td><td>Phone</td></tr>
<tr><td>joe</td><td>LA</td><td>012345</td></tr>
<tr><td>ted</td><td>NY</td><td>0124</td></tr>
</tbody></table>
<table><tbody>
<tr><td>Name</td><td>Spec</td><td>Budget</td></tr>
<tr><td>joe</td><td>i5</td><td>458</td></tr>
<tr><td>ted</td><td>i7</td><td>768</td></tr>
</tbody></table>
Javascript :
var c = document.getElementsByTagName('tbody');
var _trIndex = 1;
for ( i=0; i<c.length; i++) {
var x = c[i].rows;
for (i=0; i<x.length; i++){
x[i].setAttribute('id','tr'+_trIndex++)
}
}
Second Try :
var c = document.getElementsByTagName('tbody');
var _trIndex = 1;
for ( i=0; i<c.length; i++) {
var x = c[0].rows;
for (i=0; i<x.length; i++){
x[i].setAttribute('id','tr'+_trIndex++)
}
var y = c[1].rows;
for (i=0; i<y.length; i++){
y[i].setAttribute('id','tr'+_trIndex++)
}
}
Probably this is what you need:
// Instead of getting the table bodies, I get only the table
// rows inside the tbody elements.
var c = document.querySelectorAll('tbody tr');
// Here I check if definitely the above query found any values.
if ( c ) {
// Then I do the itteration to the found tr elements
for ( i = 0; i < c.length; i++) {
// And here I set the ID the same way you did in your example
c[i].setAttribute('id','tr'+i);
}
}
<table>
<tbody>
<tr><td>No.</td><td>Name</td><td>Score</td></tr>
<tr><td>01</td><td>ted</td><td>0.50</td></tr>
<tr><td>02</td><td>joe</td><td>0.25</td></tr>
</tbody>
</table>
<table>
<tbody>
<tr><td>Name</td><td>Address</td><td>Phone</td></tr>
<tr><td>joe</td><td>LA</td><td>012345</td></tr>
<tr><td>ted</td><td>NY</td><td>0124</td></tr>
</tbody>
</table>
<table>
<tbody>
<tr><td>Name</td><td>Spec</td><td>Budget</td></tr>
<tr><td>joe</td><td>i5</td><td>458</td></tr>
<tr><td>ted</td><td>i7</td><td>768</td></tr>
</tbody>
</table>
You can achieve this with a single line of javascript.
document.querySelectorAll("tbody tr").forEach((element, index) => element.setAttribute("id", "tr" + index));
<table>
<thead>
<tr>
<td>No.</td>
<td>Name</td>
<td>Score</td>
</tr>
</thead>
<tbody>
<tr>
<td>No.</td>
<td>Name</td>
<td>Score</td>
</tr>
<tr>
<td>01</td>
<td>ted</td>
<td>0.50</td>
</tr>
<tr>
<td>02</td>
<td>joe</td>
<td>0.25</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>Name</td>
<td>Address</td>
<td>Phone</td>
</tr>
<tr>
<td>joe</td>
<td>LA</td>
<td>012345</td>
</tr>
<tr>
<td>ted</td>
<td>NY</td>
<td>0124</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>Name</td>
<td>Spec</td>
<td>Budget</td>
</tr>
<tr>
<td>joe</td>
<td>i5</td>
<td>458</td>
</tr>
<tr>
<td>ted</td>
<td>i7</td>
<td>768</td>
</tr>
</tbody>
</table>

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.

Table sort columns horizontal

I have a problem sorting a table.
My table HTML is this:
<table>
<tr>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
</tr>
</table>
And I want it to look like this:
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</table>
Here is my current sorting code:
var rows = $('tr');
rows.eq(0).find('td').sort(function(a, b) {
return $.text([a]) > $.text([b]) ? 1 : -1;
}).each(function(newIndex) {
var originalIndex = $(this).index();
rows.each(function() {
var td = $(this).find('td');
if (originalIndex !== newIndex)
td.eq(originalIndex).insertAfter(td.eq(newIndex));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
</tr>
</table>
The code only sorts by separate rows. I can't use any plugins and I need to do this with jquery or javascript. Can anyone suggestion how to make it work?
It's simple.
Store all the numbers from td in an array.
Sort the array.
Modify the tds according to array.
Here's how you'd do it in JS:
var tds= [].slice.call(document.getElementsByTagName("td")); //Find <td> and store in array
var tdsa=tds.map(function (a) {return Number(a.innerHTML);}); //Take the innerHTMLs
tdsa.sort(); //Sort it
tds.forEach(function(a,i) {a.innerHTML=tdsa[i]}); //Modify <td>'s innerHTML
Try this - method:
get the items of the table into an array
sort the array
rebuild the rows
var columnCount = 2;
var items = [];
$('td').each(function (idx, obj) {
items.push(obj.innerHTML);
});
items.sort();
$('table tr').remove();
for(var i=0; i<items.length; i+=2) {
var row = '<tr>';
for(var j=0; j<columnCount; j++) {
row += '<td>' + items[i+j] + '</td>';
};
row += '</tr>';
$('table').append(row);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
<td>3</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
</tr>
</table>

How to overwrite the values of the first column in every rows in a HTML tbody table with JavaScript and with jQuery?

Here is a table example:
<table id="tableId">
<thead>
<tr>
<th>line number</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>value 1</td>
</tr>
<tr>
<td>3</td>
<td>value 2</td>
</tr>
<tr>
<td>1</td>
<td>value 3</td>
</tr>
</tbody>
</table>
<input type="button" value="relineing" onclick="reLineNumbering('tableId')"/>
I want only the "line number"s to be in sequence like this:
<table id="tableId">
<thead>
<tr>
<th>line number</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>value 1</td>
</tr>
<tr>
<td>2</td>
<td>value 2</td>
</tr>
<tr>
<td>3</td>
<td>value 3</td>
</tr>
</tbody>
</table>
<input type="button" value="relineing" onclick="reLineNumbering('tableId')"/>
I've tried both of the snippets below:
function reLineNumbering(tableId) {
$('#'+tableId+' tbody').each(function (i) {
this.rows[i].cells[0].text('i');
});
}
function reLineNumbering(tableId) {
var rowCount = $('#'+tableId+' tbody tr').length;
for (var i=0; i<rowCount; i++) {
$('#'+tableId+' tbody').rows[i].cells[0].text(i);
}
}
Could someone help me?
This will change the first column to a sequential number starting from 1:
function reLineNumbering(tableId){
$('#' + tableId + ' > tbody > tr').each(function(i, val){
$('td:first', this).text(i+1);
});
}
Fiddle
Plain Javascript - Fiddle:
function reLineNumbering(tableId){
var table = document.getElementById(tableId);
var total = table.rows.length;
for(var i=0; i<total; i++){
if(i > 0){
table.rows[i].cells[0].innerHTML = i;
}
}
}
Or by creating the text node instead of setting innerHTML. In this simple scenario the use of innerHTML isn't a problem, but usually you will want to work with DOM elements and set the text node instead of setting the HTML:
function reLineNumbering(tableId){
var table = document.getElementById(tableId);
var total = table.rows.length, text, cell;
for(var i=0; i<total; i++){
if(i > 0){
text = document.createTextNode(i);
cell = table.rows[i].cells[0];
cell.removeChild(cell.firstChild);
cell.appendChild(text);
}
}
}
Try
$('#tableId > tbody > tr').find('td:first').text(function(idx, text){
return idx + 1
})
Demo: Fiddle
this is the correct answer:
function reLineNumbering(tableId) {
var myTable=document.getElementById(tableId);
var rowCount = myTable.rows.length;
for (var i = 1; i < rowCount; i++) {
myTable.rows[i].cells[0].innerHTML = i;
}
}
For a VanillaJS version of the same thing:
(function(t)
{
for(var i=1;i<t.rows.length;i++)
{
t.rows[i].cells[0].innerHTML += ' Vanilla';
}
}(document.getElementById('tableId')));
Which I added to the fiddle of Arun
I post it here, because it's not an awful lot longer than the jQ version of the same code, but it is faster.
You can change it to:
var t = document.getElemebtById('tableId');
for(var i=1;i<t.rows.length;i++)
{
t.rows[i].cells[0].innerHTML = 1 + i;//number tbl
}
If you don't feel comfortable using the IIFE.
PS: the loop could be simplified to:
for(var i=1;i<t.rows.length;)//do nothing here
{
t.rows[i].cells[0].innerHTML = i++;//increment i here
}

Categories