I have a table generated in a backend. My task is to wrap text in each header column and add it to each body column cells by using .html() and .prepend(). It works as expected (you will see text in green).
Problem: Tables are generated in a backend, sometimes a table has 3 columns, sometimes 4 columns or more! How to write my Jquery dynamically in order to work on each table.
Please give me a hand. Thanks!
$(document).ready(function() {
var firstHead = $("table thead tr th:first-child").html();
var firstBodyCode = $("<span></span>").text(firstHead);
$('table tbody tr td:first-child').prepend(firstBodyCode);
var secondHead = $("table thead tr th:nth-child(2)").html();
var secondBodyCode = $("<span></span>").text(secondHead);
$('table tbody tr td:nth-child(2)').prepend(secondBodyCode);
});
table {
width: 100%;
border: 1px solid gray
}
span {
color: green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>
Use a loop to iterate over all the columns.
$(document).ready(function() {
$("table thead tr th").each(function(i) {
let bodyCode = $("<span>", {
text: $(this).text()
});
$(`table tbody tr td:nth-child(${i+1})`).prepend(bodyCode);
});
});
table {
width: 100%;
border: 1px solid gray
}
span {
color: green
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>
Related
I have create a table with following style. Now I want to get first td value as 1,2,3 using jQuery.
<html>
<head>
<style type='text/css'>
table {
counter-reset: rowNumber;
}
table tr {
counter-increment: rowNumber;
}
table tr td:first-child::before {
content: counter(rowNumber);
min-width: 1em;
margin-right: 0.5em;
}
</style>
</head>
<body>
<table border="1" id="MyTable">
<tr>
<td></td> <td>blue</td>
</tr>
<tr>
<td></td><td>red</td>
</tr>
<tr>
<td></td><td>black</td>
</tr>
</table>
</body>
</html>
I tried with following script but it showing row counter as text. How to get the value of first td?
<script>
$("#MyTable").find('tr').each(function (i, el) {
$(this).find('td:eq(0)').each(function () {
console.log(window.getComputedStyle(this, ':before').content);
});
});
</script>
Based on this:
Generated content does not alter the document tree. In particular, it is not fed back to the document language processor.
So if you see the html that generated, you will see all td is empty while you see counter (1,2,3) in page. this is html generated:
But this is result:
So generated content does not alter the document tree and you can't access to value of it.
There are lots of alternative you can do it:
$("#MyTable").find('tr').each(function (i, el) {
debugger
$(this).find('td:eq(0)').each(function (index, el) {
$(this).html(i+1)
console.log($(this).html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id="MyTable">
<tbody>
<tr>
<td></td>
<td>blue</td>
</tr>
<tr>
<td></td>
<td>red</td>
</tr>
<tr>
<td></td>
<td>black</td>
</tr>
</tbody>
</table>
Update
You can rest number after each modification on your table:
function setnumber() {
$('#MyTable tbody tr').each(function (i) {
$($(this).find('td')[0]).html(i + 1);
});
}
$(".delete").click(function () {
$(this).closest('tr').remove();
setnumber();
});
setnumber();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id="MyTable">
<tbody>
<tr>
<td></td>
<td>blue</td>
<td><span class="delete"><i class="fas fa-trash"></i>delete</span></td>
</tr>
<tr>
<td></td>
<td>red</td>
<td><span class="delete"><i class="fas fa-trash"></i>delete</span></td>
</tr>
<tr>
<td></td>
<td>black</td>
<td><span class="delete"><i class="fas fa-trash"></i>delete</span></td>
</tr>
</tbody>
</table>
Probably, you want to put 1,2,3 in TDS on DOM.
You can do like this:
$("#MyTable").find('tr').each(function (i, el) { $(el).find("td").eq(0).text(i); });
https://codesandbox.io/s/jquery-playground-forked-pmtgc?file=/src/index.js
You can use child selector to select the child of tr
jQuery("body > table > tr:nth-child(1) > td:nth-child(1)").text();
I have an HTML <table> with data. Upon clicking the table rows, I can add the clicked row to another table. But I want to highlight the row with arrow keys and, on pressing the Enter key on the highlighted row, add the data of the highlighted row to the new table.
How can I do that?
What I have tried so far:
$(document).ready(function(){
$('#myTable').focus();
});
function highlight(tableIndex) {
if ((tableIndex + 1) > $('#myTable tbody tr').length) //restart process
tableIndex = 0;
if ($('#myTable tbody tr:eq(' + tableIndex + ')').length > 0) {
$('#myTable tbody tr').removeClass('highlight');
$('#myTable tbody tr:eq(' + tableIndex + ')').addClass('highlight');
}
}
$('#goto_first').click(function() {
highlight(0);
});
$('#goto_prev').click(function() {
highlight($('#myTable tbody tr.highlight').index() - 1);
});
$('#goto_next').click(function() {
highlight($('#myTable tbody tr.highlight').index() + 1);
});
$('#goto_last').click(function() {
highlight($('#myTable tbody tr:last').index());
});
$(document).keydown(function(e) {
switch (e.which) {
case 38:
$('#goto_prev').trigger('click');
break;
case 40:
$('#goto_next').trigger('click');
break;
}
});
$(document).ready(function() {
var items = [];
$("#myTable tr").on('click', function(e) {
var newTr = $(this).closest("tr").clone();
items.push(newTr);
newTr.appendTo($("#cloneTable"));
});
})
<html><head><title>dynamictable</title>
<style>
table { cursor: pointer; }
.highlight { background-color: lightgreen; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<table id="myTable" border="1px" style="width: 30%;">
<thead>
<tr>
<th>##</th>
<th>Name</th>
<th>code</th>
<th>unit</th>
<th>rate</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>aaa</td>
<td>aa1</td>
<td>aa</td>
<td>111</td>
</tr>
<tr>
<td>1</td>
<td>aaa</td>
<td>aa1</td>
<td>aa</td>
<td>111</td>
</tr>
</tbody>
</table>
<br>
<br>
<br>
<input type="button" id="goto_first" value="first" class="btn btn-success">
<input type="button" id="goto_prev" value="prev" class="btn btn-secondary">
<input type="button" id="goto_next" value="next" class="btn btn-secondary">
<input type="button" id="goto_last" value="last" class="btn btn-success">
<br>
<br>
<br>
<table id="cloneTable" border="1px" style="width: 30%; float :left;"><!--new table to clone data-->
<thead>
<tr>
<th>##</th>
<th>Name</th>
<th>code</th>
<th>unit</th>
<th>rate</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
Here you go
// highlight first row default
$("#myTable tbody tr:first-child").addClass("highlight");
document.onkeydown = moveAndAdd;
function moveAndAdd(e) {
e = e || window.event;
if (e.keyCode == "38") {
// up arrow
activeRow = $("tr.highlight"); /* get highlighted row */
activeRow.focus();
prevRow = activeRow.prev('tr'); /*very previous siblings*/
if (prevRow.length>0) {
activeRow.removeClass("highlight"); /*remove highlight from active class */
prevRow.addClass("highlight"); /* make very prev row highlighted*/
}
} else if (e.keyCode == "40") {
// down arrow
activeRow = $("tr.highlight"); /* get highlighted row */
activeRow.focus();
nextRow = activeRow.next('tr'); /*very previous siblings*/
if (nextRow.length>0) {
activeRow.removeClass("highlight");
nextRow.addClass("highlight");
}
}
else if (e.which == 13 || e.which == 32) {
// Enter or Spacebar - edit cell
e.preventDefault();
cloneRow = $(".highlight").clone(true); /*clone highlighted row*/
$("#cloneTable").append(cloneRow.removeClass("highlight")); /*append cloned row but remove class */
}
}
table {
color:black;
background-color:white;
}
.highlight{
color:White;
background-color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable" border="1px" style="width: 30%;">
<thead>
<tr >
<th>##</th>
<th>Name</th>
<th>code</th>
<th>unit</th>
<th>rate</th>
</tr>
</thead>
<tbody>
<tr>
<td >1</td>
<td>aaa</td>
<td>aa1</td>
<td>aa</td>
<td>111</td>
</tr>
<tr>
<td>2</td>
<td>bbb</td>
<td>bb2</td>
<td>bb</td>
<td>222</td>
</tr>
<tr>
<td>3</td>
<td>ccc</td>
<td>cc3</td>
<td>cc</td>
<td>333</td>
</tr>
<tr>
<td>4</td>
<td>ddd</td>
<td>dd1</td>
<td>dd</td>
<td>444</td>
</tr>
</tbody>
</table>
<table id="cloneTable" border="1px" style="width: 30%; float :left;">
<thead>
<tr>
<th>##</th>
<th>Name</th>
<th>code</th>
<th>unit</th>
<th>rate</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I was going to write a custom response but check this out, it addresses your issue: Use arrow keys to navigate an HTML table
You're also missing a closing quotation mark around your "width: 30%" for your opening parent div
I'm trying to hide and show table rows, the following works but breaks the layout , ie the empty <td> s lose their width is there a way to prevent this?
$(document).on("click ", "tr.grey", function(e) {
e.preventDefault();
$( "tr.sales-details" ).removeClass( "show" );
$(this).nextUntil(".grey").addClass( "show" );
});
tbody tr.sales-details, tbody tr.sales-details-title{
display: none;
&.show{
display: block;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="100%" class="modal-table" id="modal-table">
<thead>
<tr><th>Surgeon name</th>
<th>Country</th>
<th>Antiquity</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr class="grey">
<td>Alex Lloyd</td>
<td>Spain</td>
<td>new client</td>
<td>2690.58 USD</td>
</tr>
<tr class="sales-details-title">
<td></td>
<td></td>
<td><strong>Seller:</strong></td>
<td><strong>Percentage:</strong></td>
</tr>
<tr class="sales-details">
<td></td>
<td></td>
<td>Support</td>
<td>2690.58 USD</td>
</tr>
</tbody>
</table>
try using {visibility:hidden} and {visibility:visible} to hide or display the elements - this will haide content but keep its place in the DOM and not cause reflowing / reformatting that disply:none causes.
tbody tr.sales-details, tbody tr.sales-details-title{
visibility: hidden;
&.show{
visibility:visible;
}
}
I know I can use the following code to remove rows in vanilla Javascript:
var table = document.getElementById('table');
function deleteRow () {
table.deleteRow(1);
};
table { background: #ccc; width: 100%; }
table thead { background: #333; color: #fff; }
table tbody { background: magenta; color: #fff; }
<button onclick="deleteRow()">Delete Row</button>
<table id="table">
<thead>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</thead>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
</table>
But this code leaves an empty tbody tag behing. JS has methods for removing thead and tfoot elements, but it seems it's missing a deleteTbody one.
How am I supposed to remove a tbody and all it's contents by using pure javascript only? No jQuery, please!
Try using:
var tbl = document.getElementById("table"); // Get the table
tbl.removeChild(tbl.getElementsByTagName("tbody")[0]); // Remove first instance of body
https://jsfiddle.net/Ltdr2qv4/1/
Use querySelectorAll() to iterate through all TBODY elements, then remove those that have no children:
var table = document.getElementById('table');
function deleteRow() {
table.deleteRow(1);
var tb = document.querySelectorAll('tbody');
for (var i = 0; i < tb.length; i++) {
if (tb[i].children.length === 0) {
tb[i].parentNode.removeChild(tb[i]);
}
}
};
table {
background: #ccc;
width: 100%;
}
table thead {
background: #333;
color: #fff;
}
table tbody {
background: magenta;
color: #fff;
}
<button onclick="deleteRow()">Delete Row</button>
<table id="table">
<thead>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</thead>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
<tbody>
<tr>
<td>lorem</td>
<td>ipsum</td>
</tr>
</tbody>
</table>
If you want to remove the tbody tag, you could select the row itself rather than the table, then use the removeChild function.
var table = document.getElementById('table');
var row = document.getElementsByTagName('tbody')[0];
function deleteRow () {
row.parentNode.removeChild(row);
};
There is no deleteTbody but there is removeChild:
var parent = document.getElementById("parent-id");
var child = document.getElementById("child-id");
parent.removeChild(child);
I hope it will help you. I am sorry. It is too late to answer.
tbody-data is tbody's id value.
$("#tbody-data tr").remove();
Fellow Gurus and Experts, I am seeking your help in attempting to move the div scroll position in the center position relative to the target Nth row (using the index) in an HTML table.
At the request of a user on this site, I have reformed my existing code to match the javascript function in question that requires further modification below.
How can I add on functionality to my existing jQuery javascript code using the function highlight() to not only highlight the specified target row, but to also move the div container scroll position in sync to the center position, relative to the target Nth row in an HTML table?
For ease of reference, I have created a fiddle as well: http://jsfiddle.net/3YbSe/1/
I am jQuery friendly :)
function highlight(tableIndex) {
// Just a simple check. If .highlight has reached the last, start again
if( (tableIndex+1) > rowCount) {
tableIndex = 0;
}
// Element exists?
if($('#data tbody tr:eq('+tableIndex+')').length > 0) {
// Remove other highlights
$('#data tbody tr').removeClass('highlight');
// Highlight your target
$('#data tbody tr:eq('+tableIndex+')').addClass('highlight');
$("#rownum").val(tableIndex+1)
}
else {
$("#rownum").val(0)
}
}
HTML Markup:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style type="text/css">
#data_container {
height: 100px;
border: 1px solid red;
width: auto;
overflow: scroll;
}
.highlight {
background-color: rgb(255,0,0);
}
</style>
<script type="text/javascript">
window.onload = function() {
var rowCount = $('#data tbody tr').length
$("#maxrows").val(rowCount)
function highlight(tableIndex) {
// Just a simple check. If .highlight has reached the last, start again
if( (tableIndex+1) > rowCount) {
tableIndex = 0;
}
// Element exists?
if($('#data tbody tr:eq('+tableIndex+')').length > 0) {
// Remove other highlights
$('#data tbody tr').removeClass('highlight');
// Highlight your target
$('#data tbody tr:eq('+tableIndex+')').addClass('highlight');
$("#rownum").val(tableIndex+1)
}
else {
$("#rownum").val(0)
}
}
$( "#data tbody tr" ).click(function() {
highlight($(this).index());
});
}
</script>
</head>
<body>
<div id="data_container">
<table id="data" border="1" cellspacing="1" cellpadding="1">
<thead>
<tr>
<th>#</th>
<th>Color</th>
<th>Fruit</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>red</td>
<td>kiwi</td>
<td>Lindsay</td>
<td>closed</td>
</tr>
<tr>
<td>2</td>
<td>blue</td>
<td>mangos</td>
<td>Sarah</td>
<td>open</td>
</tr>
<tr>
<td>3</td>
<td>green</td>
<td>oranges</td>
<td>Joseph</td>
<td>hold</td>
</tr>
<tr>
<td>4</td>
<td>yellow</td>
<td>pears</td>
<td>Jenny</td>
<td>open</td>
</tr>
<tr>
<td>5</td>
<td>orange</td>
<td>bananas</td>
<td>Mike</td>
<td>closed</td>
</tr>
<tr>
<td>6</td>
<td>purple</td>
<td>lemon</td>
<td>Jerry</td>
<td>open</td>
</tr>
<tr>
<td>7</td>
<td>teal</td>
<td>apples</td>
<td>Larry</td>
<td>hold</td>
</tr>
</tbody>
</table>
</div>
Row Number:
<br>
<input type="text" id="rownum"><br>
of
<br>
<input type="text" id="maxrows" readonly>
</body>
</html>
Ok, I think I figured out what you are trying to accomplish. You can use the position() function for this, and then a little bit of simple math. You will also need to give your table a position so that you can check the position of the highlighted <tr> to the table it's in instead of the container. Here's some codez:
//Scroll to cntr position
var trPos = $("tr.highlight").position();
var trCtr = ($("tr.highlight").height()) / 2;
var dataTblctr = ($("#data_container").height()) / 2;
$("#data_container").scrollTop(trPos.top - dataTblctr + trCtr);
DEMO