How to replace a text with row count with javascript - javascript

i have a dynamic table . that i'd add number for each tr. how can i replace the hello text with count of each tr with javascript?
here is my snippet of table:
<html>
<head></head>
<body>
<table border="1">
<tr>
<th>Rownumber</th>
<th>Name</th>
</tr>
<tr>
<th>Hello</th>
<th>A</th>
</tr>
<tr>
<th>Hello</th>
<th>B</th>
</tr>
<tr>
<th>Hello</th>
<th>C</th>
</tr>
</table>
</body>
</html>

you should be using <td> instead of <th> after the header row.
$('tr').each(function(index, row){
$(row).children('td').first().text(index);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<table border="1">
<tr>
<th>Rownumber</th>
<th>Name</th>
</tr>
<tr>
<td>Hello</td>
<td>A</td>
</tr>
<tr>
<td>Hello</td>
<td>B</td>
</tr>
<tr>
<td>Hello</td>
<td>C</td>
</tr>
</table>
</body>
</html>

Here is the solution for your problem -
var table = document.querySelector("#myTable");
var rows = table.querySelectorAll("tr");
let index = 0;
for( let row of rows){
for( let col of row.querySelectorAll("th")){
if( col.textContent == 'Hello'){
col.textContent = index;
}
}
index++;
}
<table border="1" id="myTable">
<tr>
<th>Rownumber</th>
<th>Name</th>
</tr>
<tr>
<th>Hello</th>
<th>A</th>
</tr>
<tr>
<th>Hello</th>
<th>B</th>
</tr>
<tr>
<th>Hello</th>
<th>C</th>
</tr>
</table>

You need to get all the <tr> elements within the table. Then loop through the <tr>s and starting with the second one, replace its first child's text with the index of the current <tr>.
let tableRows = document.querySelectorAll("tr")
tableRows.forEach((tr, index) => {
if(index === 0) {
//Do nothing bc you don't want to remove the text in the first table row
} else {
let firstChild = tr.children[0]
firstChild.innerText = index
}
})

You can use find("td:first") to get the numbers that would replace "Hello". Also, since its a table, you need to use td. th are used for headers:
$('tr').each(function(index, row) {
$(row).find("td:first").text(index);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<table border="1">
<tr>
<th>Rownumber</th>
<th>Name</th>
</tr>
<tr>
<td>Hello</td>
<td>A</td>
</tr>
<tr>
<td>Hello</td>
<td>B</td>
</tr>
<tr>
<td>Hello</td>
<td>C</td>
</tr>
</table>
</body>
</html>

Related

How to add a class if the number of rows in a table is some number with Javascript/jQuery

I am trying to add class to div if the number of rows in the table is larger than 3.
This is my code.
$('.box').each(function () {
var $this=$(this);
if ($this.find('tbody > tr').length > 3) {
$this.find('.box').addClass('newclass');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<table>
<thead>
<tr>
<th >1</th>
<th >2</th>
</tr>
</thead>
<tbody>
<tr>
<td>lorem1</td>
<td>ipsum1</td>
</tr>
<tr>
<td>lorem2</td>
<td>ipsum2</td>
</tr>
<tr>
<td>lorem3</td>
<td>ipsum3</td>
</tr>
<tr>
<td>lorem4</td>
<td>ipsum4</td>
</tr>
</tbody>
</table>
</div>
I don't see why this code not working, can somebody try to help me with this?
What I try to achieve is this:
<div class="box newclass">
Your code isn't working because this is a reference to the .box element itself. When you do a find() from there you're looking for child elements, so nothing it returned. To fix the issue just remove the find() call.
However you can make the jQuery more succinct by simply using the :has() selector to retrieve .box elements which have more than 3 tr within them:
$('.box:has(tbody > tr:eq(3))').addClass('newclass');
.newclass { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<table>
<thead>
<tr>
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td>lorem1</td>
<td>ipsum1</td>
</tr>
<tr>
<td>lorem2</td>
<td>ipsum2</td>
</tr>
<tr>
<td>lorem3</td>
<td>ipsum3</td>
</tr>
<tr>
<td>lorem4</td>
<td>ipsum4</td>
</tr>
</tbody>
</table>
</div>
<div class="box">
<table>
<thead>
<tr>
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td>lorem1</td>
<td>ipsum1</td>
</tr>
</tbody>
</table>
</div>
you already set the $this to the selector. and by now using $this.find will try to find inside the element itself, so u can use $this directly or search the document itself $(document).find instead of $this.find >>> try the button to show classes list
$('.box').each(function () {
var $this=$(this);
if ($this.find('tbody > tr').length > 3) {
$(document).find('.box').addClass('newclass');
}
});
$('button').on('click', function() {
console.log($(document).find('.box').attr('class'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<table>
<thead>
<tr>
<th >1</th>
<th >2</th>
</tr>
</thead>
<tbody>
<tr>
<td>lorem1</td>
<td>ipsum1</td>
</tr>
<tr>
<td>lorem2</td>
<td>ipsum2</td>
</tr>
<tr>
<td>lorem3</td>
<td>ipsum3</td>
</tr>
<tr>
<td>lorem4</td>
<td>ipsum4</td>
</tr>
</tbody>
</table>
</div>
<button> show classes list </button>

How to get a running sum on HTML table?

I searching a solution for give the running sun to a editable html table, like a spreadsheet:
Hi here is a basic example of what you want using :
The HTML content editable property.
A css class to append a focusout event to the table cell.
A simple loop to sum all values when one value changes.
$('#tbodyTest >tr').on('focusout', 'td.editable', (e) => {
let target = $(e.target),
parent_row = $(e.target).closest('tr'),
previous_row = parent_row.prev();
setTimeout(() => {
if (!isNaN(target.text())) {
$('#tbodyTest').children('tr').each((i,e)=>{
$(e).find('td').last().text(Number($(e).find('td:eq(2)').text()) +Number($(e).prev().find('td').last().text()))
})
}else{
target.text("0");
parent_row.find('td').last().text("0");
$('#tbodyTest').children('tr').each((i,e)=>{
$(e).find('td').last().text(Number($(e).find('td:eq(2)').text()) +Number($(e).prev().find('td').last().text()))
})
}
})
})
.editable {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="test" border=1>
<thead>
<th>date</th>
<th>desc</th>
<th>cost</th>
<th>running sum</th>
</thead>
<tbody id="tbodyTest">
<tr>
<td>01-01-2019</td>
<td>a</td>
<td class="editable" contenteditable='true'>1000</td>
<td>1000</td>
</tr>
<tr>
<td>01-02-2019</td>
<td>a</td>
<td class="editable" contenteditable='true'></td>
<td></td>
</tr>
<tr>
<td>01-03-2019</td>
<td>a</td>
<td class="editable" contenteditable='true'></td>
<td></td>
</tr>
<tr>
<td>01-04-2019</td>
<td>a</td>
<td class="editable" contenteditable='true'></td>
<td></td>
</tr>
</tbody>
</table>
Keep in mind that this is a basic example and you will probably add more stuff according to your needs since your ask is simple as well.
Hope it helps
Anyone still looking to this.
$('tr').each(function(index, el) {
if (index == 0) {
$(this).find('.running-balance').text($(this).find('.amount').text());
} else {
var prevRow = $(this).prev();
var prevBalance = Number(prevRow.find('.running-balance').text());
var currentAmount = Number($(this).find('.amount').text());
var newBalance = prevBalance + currentAmount;
$(this).find('.running-balance').text(newBalance.toFixed(2));
}
});
td,
th {
border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Description</th>
<th>Amount</th>
<th>Running Balance</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td class="amount">100</td>
<td class="running-balance"></td>
</tr>
<tr>
<td>b</td>
<td class="amount">150</td>
<td class="running-balance"></td>
</tr>
<tr>
<td>c</td>
<td class="amount">125</td>
<td class="running-balance"></td>
</tr>
<tr>
<td>d</td>
<td class="amount">205</td>
<td class="running-balance"></td>
</tr>
<tr>
<td>e</td>
<td class="amount">50</td>
<td class="running-balance"></td>
</tr>
</tbody>
</table>

Remove specific index child from parent DOM with removeChild() [Vanilla Javascript]

i have a table with this basic structure:
<thead>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</thead>
<body>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
and i want to remove the second child from every "tr" tag, so i would like to do something like this:
const rows = document.getElementsByTagName('td')
for (let i = 0; i < rows.length; i++) {
rows[i].removeChild(target the second child here)
}
i'm looking for a solution with pure vanilla javascript (no jquery)
You might select the tds you want to remove via a single selector string, it's probably more elegant:
document.querySelectorAll('td:nth-child(2)')
.forEach(td => td.remove());
<table>
<thead>
<tr>
<td>td1</td>
<td>td2</td>
<td>td3</td>
</tr>
</thead>
<tbody>
<tr>
<td>td1</td>
<td>td2</td>
<td>td3</td>
</tr>
<tr>
<td>td1</td>
<td>td2</td>
<td>td3</td>
</tr>
<tr>
<td>td1</td>
<td>td2</td>
<td>td3</td>
</tr>
</tbody>
</table>
If the HTML is valid, the tds will necessarily be children of trs regardless, so you don't need to specify that the td's parent is a tr.
If you want to target a specific table on the page, rather than every td in every table, just put the table identifier in front of the selector string. Eg. if the target table's ID is 'table3', then use the selector string '#table3 td:nth-child(2)' to indicate td which are the second child in their parent, which are descendants of the element with ID table3.
In VanillaJS you can use document.querySelectorAll() and walk over the 2nd td using forEach()
[].forEach.call(document.querySelectorAll('#myTable td:nth-child(2)'), function(td) {
td.remove();
});
//$("#myTable td:nth-child(2)").remove()
[].forEach.call(document.querySelectorAll('#myTable td:nth-child(2)'), function(td) {
td.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<td>TD-1</td>
<td>TD-2</td>
<td>TD-3</td>
</tr>
</thead>
<tbody>
<tr>
<td>TD-1</td>
<td>TD-2</td>
<td>TD-3</td>
</tr>
<tr>
<td>TD-1</td>
<td>TD-2</td>
<td>TD-3</td>
</tr>
<tr>
<td>TD-1</td>
<td>TD-2</td>
<td>TD-3</td>
</tr>
</tbody>
</table>
You can use a query selector with nth-child.
const rows = document.getElementsByTagName('tr')
for (let i = 0; i < rows.length; i++) {
rows[i].removeChild(rows[i].querySelector('td:nth-child(2)'));
}
<table>
<thead>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
<script>
var rows = document.getElementsByTagName('tr');
for (let i = 0; i < rows.length; i++) {
var row = rows[i];
var td = row.querySelector('td:nth-child(2)');
row.removeChild(td);
}
</script>

Inner text using javascript / jquery

I have a datatable and I want to extract the column 1
var usernames = dataTableTeamMembers.columns(1).data();
But it gives me an array like this:
Array(2)
0
:
"admin"
1
:
"catalao"
I only want the text, not the html.
How do I extract the innertext of that a tag?
There's two approaches:
With .column() (with each one):
$(document).ready(function() {
var dataTableTeamMembers = $('#example').DataTable();
dataTableTeamMembers.column(1).data().each(function(username, index){
console.log(username);
});
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tiger</td>
</tr>
<tr>
<td>2</td>
<td>Garrett</td>
</tr>
<tr>
<td>3</td>
<td>Tiger</td>
</tr>
<tr>
<td>4</td>
<td>Ashton</td>
</tr>
<tr>
<td>5</td>
<td>Garrett</td>
</tr>
</tbody>
</table>
And .columns() (returns array):
$(document).ready(function() {
var dataTableTeamMembers = $('#example').DataTable();
console.log(dataTableTeamMembers.columns(1).data()[0]);
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.16/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css"/>
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tiger</td>
</tr>
<tr>
<td>2</td>
<td>Garrett</td>
</tr>
<tr>
<td>3</td>
<td>Tiger</td>
</tr>
<tr>
<td>4</td>
<td>Ashton</td>
</tr>
<tr>
<td>5</td>
<td>Garrett</td>
</tr>
</tbody>
</table>
You have 3 options, depending on what you need
1 using DataTables API
var table = $('#your_table_id').DataTable().data();
for(var i = 0; i < table.length; i++)
{
var tbl_obj = table[i];
//do stuff
console.log(JSON.stringify(table[i]))
}
2 Using jquery to get all row html
$('#your_table_id tr').each(function() {
console.log($(this).html());
});
3 to get a specific cell on a row, by cell class
$('#your_table_id tr').each(function() {
var obj = $(this).find(".cell_class").html();
});
Use the one which fits more to your needs.

How to delete the last column in an HTML TABLE using by jquery?

I have an HTML TABLE:
<table id="persons" border="1">
<thead id="theadID">
<tr>
<th>Name</th>
<th>sex</th>
<th>Message</th>
</tr>
</thead>
<tbody id="tbodyID">
<tr>
<td>Viktor</td>
<td>Male</td>
<td>etc</td>
</tr>
<tr>
<td>Melissa</td>
<td>Female</td>
<td>etc</td>
</tr>
<tr>
<td>Joe</td>
<td>Male</td>
<td>etc</td>
</tr>
</tbody>
</table>
<input type="button" onclick="deleteLastColumn();" value="do it"/>
I need a javascript/jquery code, which delete the last column (message) in the table:
function deleteLastColumn() {
$("#theadID tr th:not(:last-child)......
$("#tbodyID tr td:not(:last-child)......
}
So the result should be this:
<table id="persons" border="1">
<thead id="theadID">
<tr>
<th>Name</th>
<th>sex</th>
</tr>
</thead>
<tbody id="tbodyID">
<tr>
<td>Viktor</td>
<td>Male</td>
</tr>
<tr>
<td>Melissa</td>
<td>Female</td>
</tr>
<tr>
<td>Joe</td>
<td>Male</td>
</tr>
</tbody>
</table>
I know there is the ":not(last)" method, but I can't find any example to my problem.
Could anyone help me?
Try
$('#persons tr').find('th:last-child, td:last-child').remove()
Demo: Fiddle
You can use this solution to achieve it easily..
function myFunction() {
var allRows = document.getElementById('my_table').rows;
for (var i=0; i< allRows.length; i++) {
allRows[i].deleteCell(-1);
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="my_table">
<thead >
<th>Column 1</td>
<th>Column 2</td>
<th>Column 3</td>
</thead >
<tr >
<td>Number 1</td>
<td>String 1</td>
<td>Decimal 1</td>
</tr>
<tr >
<td>Number 2</td>
<td>String 2</td>
<td>Decimal 2</td>
</tr>
<tr >
<td>Number 3</td>
<td>String 3</td>
<td>Decimal 3</td>
</tr>
</table><br>
<button onclick="myFunction()">Remove Last Column</button>
</body>
</html>
In addition to Arun P Johny's answer,
That would let you remove last row each time you click the button. If you just want to remove one column, not others you may try this.
function deleteLastColumn() {
$(document).find('.last').remove()
}
after adding class last to the last td and th of the table.
Demo : Fiddle

Categories

Resources