how to count table tbody tr using jquery - javascript

please suggest me
my code :
$('.Create-New-Order').click(function () {
var totalRowCount = $("#table_New_Order tbody tr").length;
alert(totalRowCount);
});

On-load table tr count
$(function() {
$('.Create-New-Order').click(function() {
var total = $('#mytbl tr').length ;
alert('tr count = '+ total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table border="1px solid red">
<tr>
<th>Name</th><th>Email</th>
</tr>
<tbody id="mytbl">
<tr>
<td>sfdsd</td><td>tsdaf#ymail.com</td>
</tr>
<tr>
<td>sfdsd</td><td>tsdaf#ymail.com</td>
</tr>
<tr>
<td>sfdsd</td><td>tsdaf#ymail.com</td>
</tr>
</tbody>
</table>
<br>
<br>
Create-New-Order

Related

Counting values from td's in jQuery

I have a problem with jQuery script. I'm trying to make a simple counting loop, for each tr. I got a table like below, and I want to select the second td, multiply it by two and add to the third td and display the result in the fourth td.
https://codepen.io/adeowsky/pen/YEgVKG
I'm trying to make it with the for each loop like below ->
<script>
(function($) {
$('.sp-league-table tbody tr').each( function() {
var pct = this.find('.data-pct').text();
console.log(pct);
//var pct = $('').hasClass('data-pct').text();
//console.log(pct);
var winy = $('.data-w').text();
var losy = $('.data-l').text();
/*var pkt = (winy*2) + (losy*2);
$('.data-pct').text(pkt);*/
});
})( jQuery );
</script>
But it doesn't work for me, where is the reason?
You are selecting all the elements with the class, not the one in the current row.
var tr = $(this);
var pCell = tr.find(".data-pct")
var wCell = tr.find('.data-w')
var lCell = tr.find('.data-l')
There are a couple of problems
Your table does not have the required class
you're not targeting the specific row's cells
You should explicitly parse the string values to integers
you've commented out the bit that does the calculation:
$(function(){
$('.sp-league-table tbody tr').each( function() {
var pct = $('.data-pct',this).text();
var winy = parseInt($('.data-w',this).text(),10);
var losy =parseInt($('.data-l',this).text(),10);
var pkt = (winy*2) + (losy*2);
$('.data-pct',this).text(pkt);
});
})
Updated: https://codepen.io/anon/pen/NwJjaO
Live example:
$(function(){
$('.sp-league-table tbody tr').each( function() {
var pct = $('.data-pct',this).text();
var winy = parseInt($('.data-w',this).text(),10);
var losy =parseInt($('.data-l',this).text(),10);
var pkt = (winy*2) + (losy*2);
$('.data-pct',this).text(pkt);
});
})
table, tr, td, th {
border: 1px solid #000;
border-collapse: collapse;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="sp-league-table">
<thead>
<tr>
<th>Name</th>
<th>W</th>
<th>L</th>
<th>PCT</th>
</thead>
<tr>
<td>Name 1</td>
<td class="data-w">12</td>
<td class="data-l">0</td>
<td class="data-pct">x</td>
</tr>
<tr>
<td>Name 2</td>
<td class="data-w">9</td>
<td class="data-l">3</td>
<td class="data-pct">x</td>
</tr>
</table>
<table class="sp-league-table">
<thead>
<tr>
<th>Name</th>
<th>W</th>
<th>L</th>
<th>PCT</th>
</thead>
<tr>
<td>Name 1</td>
<td class="data-w">12</td>
<td class="data-l">0</td>
<td class="data-pct">24</td>
</tr>
<tr>
<td>Name 2</td>
<td class="data-w">6</td>
<td class="data-l">5</td>
<td class="data-pct">17</td>
</tr>
</table>

show the column of the table in a color if the value in a cell is passed javascript

I have a table for some calculations and if cell value is passed I want to show that column of the table in a color.
I have this for the moment :
<script type="text/javascript">
$(document).ready(function(){
$('#myTable td.y_n').each(function(){
if ($(this).text() < 0.4) {
$(this).css('background-color','#a9edb8');
}
else {
$(this).css('background-color','#eda9ca');
}
});
});
</script>
but this is only for the cell.
Any idea? thanks!
If I understand your goal correctly, you want to set the background color of an entire column if one if the y_n cells contains a numeric value and choose the color based on that value.
To set the entire column, you could get the tablecells at the corresponding indices, but easier is to use a column group:
$(document).ready(function(){
var cols = $('#myTable col'); //get the column groups
$('#myTable td.y_n').each(function(){
var text = this.innerText; //text of the td
if(text.length > 0 && !isNaN(this.innerText)){ //check if it's a number
var ind = $(this).index(); //the index of the td inside its tr = the column index
$(cols[ind]).css('background-color', parseFloat(text) < 0.4 ? '#a9edb8' : '#eda9ca'); //set the col of the column group
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<colgroup>
<col>
<col>
<col>
</colgroup>
<tr>
<td>r1</td>
<td class='y_n'></td>
<td class='y_n'>.7</td>
</tr>
<tr>
<td>r2</td>
<td class='y_n'>.1</td>
<td class='y_n'>.6</td>
</tr>
<tr>
<td>r3</td>
<td>a</td>
<td>b</td>
</tr>
</table>
$(document).ready(function() {
$('#myTable td.y_n').each(function(i,v) {
if (parseFloat($(this).text()) < 0.4) {
$(this).closest("table").find("td").eq(i).addClass("pass");
} else {
$(this).closest("table").find("td").eq(i).addClass("fail");
}
});
});
.pass {
background-color: #a9edb8
}
.fail {
background-color: #eda9ca
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<td class='y_n'>
.3
</td>
<td class='y_n'>
.6
</td>
</tr>
<tr>
<td class='y_n'>
.2
</td>
<td class='y_n'>
.9
</td>
</tr>
<tr>
<td class='y_n'>
.9
</td>
<td class='y_n'>
.1
</td>
</tr>
</table>
Use parseFloat() then compare
You can also achieve like this. in each i is index and e will be current element. And i just added with="100" to table so its looks proper.
$(document).ready(function() {
$('#myTable td.y_n').each(function(i,e) {
if ($(e).text() < 0.4) {
$(e).css('background-color','#a9edb8');
} else {
$(e).css('background-color','#eda9ca');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable" width="100">
<tr>
<td class='y_n'>
.3
</td>
</tr>
<tr>
<td class='y_n'>
.6
</td>
</tr>
</table>
I am not saying this is the best way because i have use so many loops, but you can achieve your requirement by this code.
$(document).ready(function() {
$('#myTable tr').each(function(index,event) {
$(event).children('td').each(function(indexI,eventI) {
if ($(eventI).text() < 0.4) {
$('#myTable tr').each(function(indexIn,eventIn) {
$(eventIn).children('td').eq(indexI).css('background- color','#eda9ca');
});
}
});
});
});
Best of luck :)
If there are many rows (a lot of them) in your table, you might be better of using colgroups with col structure in your table, and put the background on the col-element. Anyway, you can always do this:
$(function() {
$('table a').click(function(e) {
e.preventDefault();
var index = $(this).html();
colHighlight($(this).closest('table'), index);
});
});
function colHighlight(table, colIndex) {
var bodyCells = table.find('tbody td');
bodyCells.css('background-color', 'transparent');
bodyCells.filter(':nth-child(' + colIndex + ')').css({
'background-color': 'yellow'
});
}
table, td, th {
border: 1px solid #000;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Head 1</th>
<th>Head 2</th>
<th>Head 3</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="3">
Highlight column:
1
2
3
</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
</tr>
</tbody>
</table>

Loop HTML table and add the identical items and its calculated amount to another table

<html>
<body>
<div>
<table border="1" id="topTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="topTableBody">
<tr>
<td>Apples</td>
<td>50</td>
</tr>
<tr>
<td>Apples</td>
<td>25</td>
</tr>
<tr>
<td>Oranges</td>
<td>30</td>
</tr>
<tr>
<td>Strawberry</td>
<td>60</td>
</tr>
<tr>
<td>Cherry</td>
<td>10</td>
</tr>
<tr>
<td>Guava</td>
<td>5</td>
</tr>
<tr>
<td>Strawberry</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
<button id="btn">Click</button>
</br>
<div>
<table border="1" id="bottomTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="bottomTableBody">
</tbody>
</table>
</div>
</body>
</html>
When I press on the button I want it to loop through the top table and get the item names that're alike and add them in one row with the sold amount combined in the bottom table ex: apples will have their own row with a sold amount of 75 and others who have no names that're alike will have their own row such as Oranges with the sold amount also.
If you can use JQuery.
(JSFiddle: http://jsfiddle.net/inanda/o9axgkaz/):
jQuery('#btn').on('click', function() {
var sumMap = {};
//Iterate through table rows
$("table tbody tr").each(function () {
if (sumMap[$(this).children('td:nth-child(1)').text()]) {
sumMap[$(this).children('td:nth-child(1)').text()] = sumMap[$(this).children('td:nth-child(1)').text()] +Number($(this).children('td:nth-child(2)').text());
} else {
sumMap[$(this).children('td:nth-child(1)').text()] = Number($(this).children('td:nth-child(2)').text());
}
})
//Append result to the other table
$.each(sumMap, function (i, val) {
$('#bottomTable tr:last').after('<tr><td>'+i+'</td><td>'+val+'</td>');
});
});
Pure javascript:
(JSFiddle: http://jsfiddle.net/inanda/2dmwudfj/ ):
appendResultToBottomTable= function() {
var sumMap = calculate();
appendResultToTable('bottomTableBody', sumMap);
}
function calculate() {
var table = document.getElementById("topTableBody");
var map = {};
for (var i = 0, row; row = table.rows[i]; i++) {
var itemType=(row.cells[0].innerText || row.cells[0].textContent);
var value=(row.cells[1].innerText || row.cells[1].textContent);
if (map[itemType]) {
map[itemType] = map[itemType] +Number(value);
} else {
map[itemType] = Number(value);
}
}
return map;
}
function appendResultToTable(tableId, sumMap){
var table = document.getElementById(tableId);
for (var item in sumMap){
var row = table.insertRow(table.rows.length);
var cellItem = row.insertCell(0);
var cellValue = row.insertCell(1);
cellItem.appendChild(document.createTextNode(item));
cellValue.appendChild(document.createTextNode(sumMap[item]));
}
}
If it is applicable for your project to use external libraries, you can do it with code like below:
alasql('SELECT Item,SUM(CONVERT(INT,Sold)) AS Sold \
INTO HTML("#res",{headers:true}) \
FROM HTML("#topTable",{headers:true}) \
GROUP BY Item');
Here:
SELECT Item, SUM(Sold) FROM data GROUP BY Item is a regular SQL expression to group and sum data from the table
CONVERT(INT,Sold) conversion procedure from string to INT type
FROM HTML() and INTO HTML() special functions to read/write data from/to HTML table, {headers:true} is a parameter to use headers
I added some minor CSS code (for table and cells borders), because Alasql generates the "plain" HTML table.
See the working snippet below.
(Disclaimer: I am an author of Alasql library)
function run() {
alasql('SELECT Item,SUM(CONVERT(INT,Sold)) AS Sold INTO HTML("#res",{headers:true}) FROM HTML("#topTable",{headers:true}) GROUP BY Item');
}
#res table {
border:1px solid black;
}
#res table td, th{
border:1px solid black;
}
<script src="http://alasql.org/console/alasql.min.js"> </script>
<div>
<table border="1" id="topTable">
<thead>
<th>Item</th>
<th>Sold</th>
</thead>
<tbody id="topTableBody">
<tr>
<td>Apples</td>
<td>50</td>
</tr>
<tr>
<td>Apples</td>
<td>25</td>
</tr>
<tr>
<td>Oranges</td>
<td>30</td>
</tr>
<tr>
<td>Strawberry</td>
<td>60</td>
</tr>
<tr>
<td>Cherry</td>
<td>10</td>
</tr>
<tr>
<td>Guava</td>
<td>5</td>
</tr>
<tr>
<td>Strawberry</td>
<td>20</td>
</tr>
</tbody>
</table>
</div>
<button id="btn" onclick="run()">Click</button>
</br>
<div id="res"></div>

Adding a row that is writable in HTML

I have made a table that can add a row. But I want the row to be writable. When the user clicks the addRow a new row will appear and the user can input a text on it. Can someone help me to do it? Thankyou so much.
the code is in the jsFiddle.
jsFiddle
Here is the solution in jsFiddle
http://jsfiddle.net/96oqxz9z/
All you need to add is a simple line:
$('#tbl1').append("<TR><TD></TD><TD><input type=\"text\"></TD></TR>");
Try this
Check here
function addRow() {
$('#addmore').append('<tr><td><input type="text" value="1"></td><td><input type="text" value="2"></td></tr><tr><td> </td></tr>')
};
$(document).on('click', '#add', function() {
var row = '<tr><td><input type="text" /></td></tr>';
$(this).closest('table').append(row);
})
td {
border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="add">add row </td>
</tr>
</table>
try using this:
function addRow() {
"use strict";
var table = document.getElementById("tbl1");
var row=table.insertRow(table.rows.length);
console.log(row);
var td1=row.insertCell(0);
var td11 = document.createElement("span");
td1.appendChild(td11);
var td2=row.insertCell(1);;
var td22 = document.createElement("input");
td22.type = "text";
td2.appendChild(td22);
td11.innerHTML = document.getElementById("a").innerHTML;
td2.value = document.getElementById("b").innerHTML;
row.appendChild(td1);
row.appendChild(td2);
table.children[0].appendChild(row);
}
<input type="button" onclick="addRow()" value="Add Row"/>
<TABLE id="tbl1">
<TR>
<TH></TH>
<TH id="a">Principal Name</TH>
<TH id="b">Principal Titles</TH>
</TR>
<TR>
<TD></TD>
<TD>Director Of Manager</TD>
</TR>
<TR>
<TD></TD>
<TD>President</TD>
</TR>
<TR>
<TD></TD>
<TD>Treasurer</TD>
</TR>
</TABLE>

Sum total for column in jQuery

The following code isn't working. I need to sum all by column as you can see on jsfiddle. What's going wrong?
HTML
<table id="sum_table" width="300" border="1">
<tr>
<td>Apple</td>
<td>Orange</td>
<td>Watermelon</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr class="totalColumn">
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</table>
Javascript
$(document).ready(function(){
$(".rowDataSd").each(function() {
newSum.call(this);
});
});
function newSum() {
var $table = $(this).closest('table');
var total = 0;
$(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalColumn) .rowDataSd').each(function() {
total += parseInt($(this).html());
});
$table.find('.totalColumn td:nth-child('')').html(total);
}
Here is a jsffile. hope this helps
<table id="sum_table" width="300" border="1">
<tr class="titlerow">
<td>Apple</td>
<td>Orange</td>
<td>Watermelon</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">2</td>
<td class="rowDataSd">3</td>
</tr>
<tr>
<td class="rowDataSd">1</td>
<td class="rowDataSd">5</td>
<td class="rowDataSd">3</td>
</tr>
<tr class="totalColumn">
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
<td class="totalCol">Total:</td>
</tr>
</table>
<script>
var totals=[0,0,0];
$(document).ready(function(){
var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");
$dataRows.each(function() {
$(this).find('.rowDataSd').each(function(i){
totals[i]+=parseInt( $(this).html());
});
});
$("#sum_table td.totalCol").each(function(i){
$(this).html("total:"+totals[i]);
});
});
</script>
jsFiddle with example
To achieve this, we can take full advantage of the thead and tfoot tags within the table element. With minor changes, we have the following:
HTML
<table id="sum_table" width="300" border="1">
<thead>
<tr>
<th>Apple</th>
<th>Orange</th>
<th>Watermelon</th>
</tr>
</thead>
<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>
<tfoot>
<tr>
<td>Total:</td>
<td>Total:</td>
<td>Total:</td>
</tr>
</tfoot>
</table>​​​​​​​​​​​​​​​
This then allows us to target more specifically the elements we want, i.e. how many columns are there, and what is the "total" cell.
JavaScript
$(document).ready(function()
{
$('table thead th').each(function(i)
{
calculateColumn(i);
});
});
function calculateColumn(index)
{
var total = 0;
$('table tr').each(function()
{
var value = parseInt($('td', this).eq(index).text());
if (!isNaN(value))
{
total += value;
}
});
$('table tfoot td').eq(index).text('Total: ' + total);
}​
$('#sum_table tr:first td').each(function(){
var $td = $(this);
var colTotal = 0;
$('#sum_table tr:not(:first,.totalColumn)').each(function(){
colTotal += parseInt($(this).children().eq($td.index()).html(),10);
});
$('#sum_table tr.totalColumn').children().eq($td.index()).html('Total: ' + colTotal);
});
Live example: http://jsfiddle.net/unKDk/7/
An alternate way:
$(document).ready(function(){
for (i=0;i<$('#sum_table tr:eq(0) td').length;i++) {
var total = 0;
$('td.rowDataSd:eq(' + i + ')', 'tr').each(function(i) {
total = total + parseInt($(this).text());
});
$('#sum_table tr:last td').eq(i).text(total);
}
});
Example: http://jsfiddle.net/lucuma/unKDk/10/
This is easily accomplished with a little tweaking of the classes on your table:
HTML:
<table id="sum_table" width="300" border="1">
<tr>
<td>Apple</td>
<td>Orange</td>
<td>Watermelon</td>
</tr>
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
</tr>
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
</tr>
<tr>
<td class="col1">1</td>
<td class="col2">2</td>
<td class="col3">3</td>
</tr>
<tr>
<td class="total">Total:</td>
<td class="total">Total:</td>
<td class="total">Total:</td>
</tr>
</table>​
JS:
var getSum = function (colNumber) {
var sum = 0;
var selector = '.col' + colNumber;
$('#sum_table').find(selector).each(function (index, element) {
sum += parseInt($(element).text());
});
return sum;
};
$('#sum_table').find('.total').each(function (index, element) {
$(this).text('Total: ' + getSum(index + 1));
});
http://jsfiddle.net/unKDk/9/
I know this has been well answered by now, but I started working on this solution earlier before all the answers came through and wanted to go ahead and post it.
This solution works with the HTML as you posted it, and assumes 4 things: 1) the first row is the header row, 2) the last row is the totals row, 3) each row has equal columns, and 4) the columns contain integers. In this case, only the table needs to be identified.
$(document).ready(function(){
totalRows("#sum_table");
});
function totalRows(tableSelector) {
var table = $(tableSelector);
var rows = table.find("tr");
var val, totals = [];
//loop through the rows getting values in the rowDataSd columns
rows
.each(function(rIndex) {
if (rIndex > 0 && rIndex < (rows.length-1)) { //not first or last row
//loop through the columns
$(this).find("td").each(function(cIndex) {
val = parseInt($(this).html());
(totals.length>cIndex) ? totals[cIndex]+=val : totals.push(val);
});
}
})
.last().find("td").each(function(index) {
val = (totals.length>index) ? totals[index] : 0;
$(this).html( "Total: " + val );
});
}
​
​
Here you go sir! http://jsfiddle.net/47VDK/

Categories

Resources