for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>")
tr.append("<td>1</td>");
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody></tbody>
</table>
How Can I append rows and then dynamically change the rowspan of every second row. What I want to happend is it will look like below:
<table border='1'>
<tbody>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td rowspan="2">1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
</tr>
</tbody>
</table>
I tried using index but it is not adding the rowspan
Any help is appreciated.
FYI : What I want to happened is append first then change the row span after the row is appended
Just added mod (%)
for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>");
if(i%2===0){
tr.append("<td rowspan='2'>1</td>");
}
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
td, th {
border: 1px solid #ddd;
padding: 8px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table>
<tbody></tbody>
</table>
</body>
</html>
I hope I achieve what you need.
I base the result from your second snippet.
for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>")
tr.append("<td>1</td>");
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
$('button').click(function(){
$('table tr:odd td:first-child').remove();
$('table tr:even td:first-child').attr('rowspan', 2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<tbody></tbody>
</table>
<button>append</button>
try to use html string and then attach it to your element and make the rowspan dynamic for example :
var html_string = '<tr>'
for (var i = 0; i < 10; i++) {
html_string+= '<td rowspan="'+i+'">1</td>'
html_string += '<td>2</td>'
}
html_string +='</tr>'
$("table tbody").append(html_string)
Below code may help,
for (var i = 0; i < 10; i++) {
var tr = $("<tr></tr>");
tr.append("<td>1</td>");
tr.append("<td>2</td>");
$("table tbody").append(tr)
}
$('table tr:odd td:first-child').remove();
$('table tr:even td:first-child').attr('rowspan', 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border='1'>
<tbody></tbody>
</table>
Related
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>
The td:nth-child('n') is not working over in my table it gives null in the log Where as it is working when i use children[n] it is a simple function for searching
I couldn't find the reason why it is giving out a null.. Here is the code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Table Searching</title>
<style>
th{
font-weight: bolder;
}
table, th, td{
font-size: 20px;
border: 2px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<input type="text" name="search">
<button class="s" onclick="Search()">Search by Name</button>
<button class="s" onclick="Search()">Search by Country</button>
<button class="s" onclick="Search()">Search by Pet</button>
<table>
<tr>
<th>Name</th>
<th>Country</th>
<th>Pet</th>
</tr>
<tr>
<td>Abhi</td>
<td>Canada</td>
<td>koala</td>
</tr>
<tr>
<td>Riya</td>
<td>France</td>
<td>Parrot</td>
</tr>
<tr>
<td>Sid</td>
<td>UK</td>
<td>Pig</td>
</tr>
<tr>
<td>Kritika</td>
<td>Germany</td>
<td>Cat</td>
</tr>
<tr>
<td>Kartik</td>
<td>China</td>
<td>Frog</td>
</tr>
<tr>
<td>Radhika</td>
<td>India</td>
<td>Dog</td>
</tr>
</table>
<script>
var input=document.getElementsByName("search")[0];
var s=document.getElementsByClassName("s");
var n=0;
function Search(){
for (var j=0; j<s.length; j++)
{
console.log("element");
console.log(s[j]);
console.log("target");
console.log(event.target);
if(s[j]==event.target){
n=j;
console.log(n);
}
}
var val= input.value;
var a=document.querySelectorAll("table > tbody > tr");
console.log(a);
for(var i =0; i<a.length; i++)
{
var d = a[i].querySelector('td:nth-child("+n+")');
console.log(d);
if(d.innerHTML.toLowerCase()==val.toLowerCase()){
a[i].style.display="";
}
else
{
a[i].style.display="none";
}
}
}
</script>
</body>
</html>
Here are the three reasons why you are giving out null in your code:
First, as stated by Satpal, this code 'td:nth-child("+n+")' will not replace n by its value. It's like writing td:nth-child("+n+") in css.
The solution for this is to write: 'td:nth-child(' + n + ')'. You then concatenate the value of n with the rest of the string
The value of n is an index in a array, so it starts at 0 and ends at array.length - 1. The problem is that the nth-child selector actually selects the nth-child (brilliant naming), so if n is 0 (in the case of searching by name), you'll try to select the 0th-child, wihich doesn't exist... You then have to write: 'td:nth-child(' + (n + 1) + ')' or change the definition of n
You have no <tbody> tag in your HTML. Which means that all the content of the table will be wrapped in a tbody and your selector document.querySelectorAll("table > tbody > tr")will also selects the header of your table. To avoid that, change your HTML accordingly.
Something like that:
<table>
<thead>
<tr>
<th>Name</th>
<th>Country</th>
<th>Pet</th>
</tr>
</thead>
<tbody>
<tr>
<td>Abhi</td>
<td>Canada</td>
<td>koala</td>
</tr>
<tr>
<td>Riya</td>
<td>France</td>
<td>Parrot</td>
</tr>
<tr>
<td>Sid</td>
<td>UK</td>
<td>Pig</td>
</tr>
<tr>
<td>Kritika</td>
<td>Germany</td>
<td>Cat</td>
</tr>
<tr>
<td>Kartik</td>
<td>China</td>
<td>Frog</td>
</tr>
<tr>
<td>Radhika</td>
<td>India</td>
<td>Dog</td>
</tr>
</tbody>
</table>
Here is a jsfiddle where the search works fine: https://jsfiddle.net/n23685b6/1/
Hope this helps!
scrollToNthChild = (): * => {
var tableBody = document.getElementById('event-table-body');
var tableRows = tableBody.getElementsByTagName('tr');
let targetElement = tableRows[7];
targetElement.scrollIntoView();
}
I am adding values to table like:
Item,Quantity,Price,TotalPrice
Now there are multiple rows: How can i sum TotalPrice of all to get GrandTotal using Jquery.
Code:
$("#Product").append(" <tr><td id='clientname'>" +ClientName+ "</td> <td id='item'>"+ItemName+"</td> <td id='quantity'>"+Quantity+"</td> <td id='price'>"+Price+"</td> <td id='totalprice'>"+TotalPrice+"</td> <td> <a onClick='deleteRow(this);'>Delete</a> </td> </tr>");
Its possible when i insert new row data its show grand total in textbox/label,Like:
function TotalPriceCalc()
{
var lblTotalPrice = document.getElementById('lblTotalPrice');
lblTotalPrice.value = sum;
}
Here's an example that will sum whatever column index you provide.
$(function() {
$("#subtotal").html(sumColumn(4));
$("#total").html(sumColumn(5));
});
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="border-spacing: 10px;">
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>12</td>
<td>34</td>
</tr>
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>56</td>
<td>78</td>
</tr>
<tr>
<td>ClientName</td>
<td>ItemName</td>
<td>Quantity</td>
<td>90</td>
<td>12</td>
</tr>
<tr>
<td colspan="3">Totals</td>
<td id="subtotal"></td>
<td id="total"></td>
</tr>
</table>
After you use class= instead of id= .Cause ID MUST be unique. you need to loop through each row and find totalPrice
$(document).ready(function(){
var TotalValue = 0;
$("#Product tr").each(function(){
TotalValue += parseFloat($(this).find('.totalprice').text());
});
alert(TotalValue);
});
While you tagged Jquery .. This is a Jquery solution so please be sure to include Jquery
You should use classes, not IDs, to name repeated elements. So it should be:
...<td class="totalprice">'+TotalPrice+'</td>...
Then you can do
function TotalPriceCalc() {
var total = 0;
$(".totalprice").each(function() {
total += parseFloat($(this).text());
});
$("#lblTotalPrice").val(total);
}
Have look, this is our table
<table class="table table-bordered">
<thead>
<tr>
<th>1</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td id="loop">50</td>
</tr>
<tr>
<td>1</td>
<td id="loop">60</td>
</tr>
<tr>
<td>1</td>
<td id="loop">70</td>
</tr>
</tbody>
<tbody>
<tr>
<td class="text-right">Total</td>
<td></td>
</tr>
</tbody>
And this is loop to have sum of price
$(function() {
var TotalValue = 0;
$("tr #loop").each(function(index,value){
currentRow = parseFloat($(this).text());
TotalValue += currentRow
});
console.log(TotalValue);
});
I have a table with multiple values and table values are moved from one table to another. When it returns to initial table then I need to sort this table based on the alphabetical order.
I am using this code but it doesn't work for me:
var aa = $("#unSelectedTab").find('td');
var abc = '';
for (var i = 0; i < aa.length; i++) {
abc += aa[i].attr("id");
}
It's a lot of code but this should do it:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.9.0.js"></script>
<meta content="text/html; charset=UTF-8" http-equiv="content-type">
<title>Example</title>
</head>
<body>
<table>
<tbody>
<tr><th>number</th><th>letter</th></tr>
<tr>
<td>3</td>
<td>a</td>
</tr>
<tr>
<td>2</td>
<td>c</td>
</tr>
<tr>
<td>2</td>
<td>c</td>
</tr>
<tr>
<td>2</td>
<td>b</td>
</tr>
<tr>
<td>3</td>
<td>b</td>
</tr>
<tr>
<td>1</td>
<td>c</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function helper_getText(el){
return (el.innerText)?el.innerText:el.textContent;
}
function sortTable(table,byCols){
var rows=table.getElementsByTagName("tr"),
rowArr=[],
i,rowValues=[],j,cells,
tbody=table.getElementsByTagName("tbody")[0];
for(i=0;i<rows.length;i++){
cells=rows[i].getElementsByTagName("td");
if(cells.length===0){
continue;
}else{
rowArr.push($.clone(rows[i]));
rows[i].parentElement.removeChild(rows[i]);
i--;
}
rowValues.push({vals:[],index:rowValues.length});
for(j=0;j<byCols.length;j++){
rowValues[rowValues.length-1].vals.push(
// here you can get the attribute instead
// if there are multiple attributes per column
// to sort on then this gets more difficult
// $.trim(cells[byCols[j]].document.body.getAttribute("data-something"))
$.trim(helper_getText(cells[byCols[j]]))
);
}
}
//sort by multiple columns should be seporate function
rowValues.sort(function(a,b){
var i = 0;
while(a.vals[i]==b.vals[i]&&i<a.vals.length){
i++;
}
if(i===a.vals.length){return 0};
return (a.vals[i]>b.vals[i])?1:-1;
});
//add the rows in the right order
for(i=0;i<rowValues.length;i++){
tbody.appendChild(rowArr[rowValues[i].index]);
}
}
//[1,0] means sort by colum 2 first than by colum 1
sortTable(document.getElementsByTagName("table")[0],[1,0]);
</script>
</body>
</html>
Good Evening, i want to get all the data from the row that the user clicks on, so i tried this script, it gets the row id but it doesn't get the data exists in that row, i push every data in that row to an array for further uses:
function findRowNumber() {
var rowIdx;
var rowData = new Array();
var table = document.getElementById('product_table');
var rows = table.getElementsByTagName('tr');
var selectedRow;
var rowCellValue;
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
rowIdx = this.rowIndex;
selectedRow = rows[rowIdx];
for (j = 1; j < selectedRow.length; j++) { // it doesn't enter that loop
rowCellValue = selectedRow.cells[j].value;
rowData.push(rowCellValue);
alert("Value " + rowCellValue);
}
}
}
}
selectedRow is populated after you click the row, while you are trying to loop trough it after binding the click handler, but before the actual click. You have to move that code in the click handler
If the data in the cells is text,
it may be simpler to retrieve with textContent(or innerText).
<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title> Small Test Page</title>
<style>
table{border:3px ridge #c0c0c0;border-collapse:collapse;}
th, td{border:1px solid black}
</style>
<script>
function findRowNumber(){
var rowIdx;
var rowData= [];
var table= document.getElementById('product_table');
var rows= table.getElementsByTagName('tr');
var selectedRow;
var rowCellValue;
for(i= 0;i<rows.length;i++){
rows[i].onclick= function(){
rowIdx= this.rowIndex;
selectedRow= this.cells;
for(j= 0;j<selectedRow.length;j++){
rowCellValue= selectedRow[j].textContent ||
selectedRow[j].innerText;
rowData.push('cell '+j+': '+rowCellValue);
}
alert("Row #" +rowIdx+'. '+ rowData);
}
}
}
</script>
</head>
<body>
<h1> Retrieve Row Data</h1>
<p> <button type= "button" id= "tableSwapBtn" onclick= "findRowNumber()">
Click to initialize</button> </p>
<table id="product_table" style="width:300px">
<tbody>
<tr> <td> a</td> <td> 1</td> </tr>
<tr> <td> b</td> <td> 2</td> </tr>
<tr> <td> c</td> <td> 3</td> </tr>
<tr> <td> d</td> <td> 4</td> </tr>
<tr> <td> e</td> <td> 5</td> </tr>
<tr> <td> f</td> <td> 6</td> </tr>
<tr> <td> g</td> <td> 7</td> </tr>
</tbody>
</table>
</body>
</html>