This is my pagination
pagination.js
$(document).ready(function() {
var totalRows = $('#myTable').find('tbody tr:has(td)').length;
var recordPerPage = 10;
var totalPages = Math.ceil(totalRows / recordPerPage);
var $pages = $('<div id="pages"></div>');
for (i = 0; i < totalPages; i++) {
$('<span class="pageNumber"> ' + (i + 1) + '</span>').appendTo($pages);
}
$pages.appendTo('#myTable');
$('.pageNumber').hover(
function() {
$(this).addClass('focus');
},
function() {
$(this).removeClass('focus');
}
);
$('table').find('tbody tr:has(td)').hide();
var tr = $('table tbody tr:has(td)');
for (var i = 0; i <= recordPerPage - 1; i++) {
$(tr[i]).show();
}
$('span').click(function(event) {
$('#myTable').find('tbody tr:has(td)').hide();
var nBegin = ($(this).text() - 1) * recordPerPage;
var nEnd = $(this).text() * recordPerPage - 1;
for (var i = nBegin; i <= nEnd; i++) {
$(tr[i]).show();
}
});
});
Table.php
<table id="myTable" class="table table-bordered " width="100%" cellspacing="0">
</table>
Hello Guys, Can anyone help with this problem. I'm doing pagination in may patient table but my pagination is in my picture above. I want my pagination to start to "Previous 1 2 3 Next" but in my pagination is only " 1 2 3". I want to add Previous and Next. Sorry Guys, I'm just a beginner.
In my example I'm using a table with just 10 entries and recordPerPage is set to 2 for convenience. If there is no previous or next page, previous and next simply don't work. It could be adjusted to not show previous or next instead but maybe this isn't necessary and you're already content with this solution.
$(document).ready(function() {
var totalRows = $('#myTable').find('tbody tr:has(td)').length;
var recordPerPage = 2;
var totalPages = Math.ceil(totalRows / recordPerPage);
var $pages = $('<div id="pages"></div>');
for (i = 0; i < totalPages; i++) {
$('<span class="pageNumber"> ' + (i + 1) + '</span>').appendTo($pages);
}
var next = $('<span class="next" data-target="2">Next</span>');
next.appendTo($pages);
var prev = $('<span class="prev" data-target="0">Previous</span>');
prev.prependTo($pages);
$pages.appendTo('#myTable');
$('.pageNumber').hover(
function() {
$(this).addClass('focus');
},
function() {
$(this).removeClass('focus');
}
);
$('table').find('tbody tr:has(td)').hide();
var tr = $('table tbody tr:has(td)');
for (var i = 0; i <= recordPerPage - 1; i++) {
$(tr[i]).show();
}
$('span.pageNumber').click(function(event) {
$('#myTable').find('tbody tr:has(td)').hide();
var nBegin = ($(this).text() - 1) * recordPerPage;
var nEnd = $(this).text() * recordPerPage - 1;
for (var i = nBegin; i <= nEnd; i++) {
$(tr[i]).show();
}
$(".next").data("target", parseInt($(this).text()) + 1);
$(".prev").data("target", parseInt($(this).text()) - 1);
});
$('span.next').click(function(event) {
if ($(this).data("target") <= $(".pageNumber:last").text()) {
$('#myTable').find('tbody tr:has(td)').hide();
var nBegin = ($(this).data("target") - 1) * recordPerPage;
var nEnd = $(this).data("target") * recordPerPage - 1;
for (var i = nBegin; i <= nEnd; i++) {
$(tr[i]).show();
}
$(this).data("target", $(this).data("target") + 1);
$(".prev").data("target", $(".prev").data("target") + 1);
}
});
$('span.prev').click(function(event) {
if ($(this).data("target") >= $(".pageNumber:first").text()) {
$('#myTable').find('tbody tr:has(td)').hide();
var nBegin = ($(this).data("target") - 1) * recordPerPage;
var nEnd = $(this).data("target") * recordPerPage - 1;
for (var i = nBegin; i <= nEnd; i++) {
$(tr[i]).show();
}
$(this).data("target", $(this).data("target") - 1);
$(".next").data("target", $(".next").data("target") - 1);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
<tr>
<td>5</td>
</tr>
<tr>
<td>6</td>
</tr>
<tr>
<td>7</td>
</tr>
<tr>
<td>8</td>
</tr>
<tr>
<td>9</td>
</tr>
<tr>
<td>10</td>
</tr>
</table>
This may not answer your question directly but as your question says you are a beginner with JavaScript. As a beginner I'd always try to use existing plugins / librarys which solve my problems before I attempt solving them by myself.
The easiest solution for your problem would be to use something like Datatables. It offers great support for customizing and also comes with your desired pagination out-of-the-box.
If you need help converting your code to datatables ask a new question.
Related
function connectThem() {
alert('(' + markedCells[0] +') и (' + markedCells[1] + ')');
if (markedCells.length == 2) {
y_distance = markedCells[0][0] - markedCells[1][0];
y_distance = Math.abs(y_distance) + 1; // vertical distance between dots
x_distance = markedCells[0][1] - markedCells[1][1];
x_distance = Math.abs(x_distance) + 1; // horizontal distance between dots
if (x_distance > y_distance) { // if horizontal distance is bigger than vertical distance
markedCells.sort(function(a,b){return a[1] - b[1];});
totalRows = y_distance;
for (var row = 0 ; row < y_distance; row++) {
thisRowLength = Math.floor(x_distance / totalRows);
for (var c = 0; c < thisRowLength; c++) {
document.getElementById('cell-' + markedCells[0][0] + '-' + markedCells[0][1]).style.backgroundColor = "red";
markedCells[0][1] = parseInt(markedCells[0][1]) + 1;
}
if (markedCells[0][0] < markedCells[1][0]) { // if first marked dot is higher
markedCells[0][0] = parseInt(markedCells[0][0]) + 1;
}
else { // if second one is higher
markedCells[0][0] = parseInt(markedCells[0][0]) - 1;
}
totalRows -= 1; // vertical remaining
x_distance -= thisRowLength; // horizontal remaining
}
}
else {
markedCells.sort(function(a,b){return a[0] - b[0];});
totalCols = x_distance;
for (var col = 0; col < x_distance; col++) {
thisColLength = Math.floor(y_distance/totalCols);
for (var r = 0; r < thisColLength; r++) {
document.getElementById('cell-' + markedCells[0][0] + '-' + markedCells[0][1]).style.backgroundColor = "red";
markedCells[0][0] = parseInt(markedCells[0][0]) + 1;
}
if (markedCells[0][1] < markedCells[1][1]) { // if first marked dot is higher
markedCells[0][1] = parseInt(markedCells[0][1]) + 1;
}
else { // if second one is higher
markedCells[0][1] = parseInt(markedCells[0][1]) - 1;
}
totalCols -= 1;
y_distance -= thisColLength;
}
}
}
else { // if more or less than 2 dots to connect
alert("Can't connect " + markedCells.length + " dots");
}
}
This is my ugly code that does the following thing: I mark 2 cells in a table and the script connects those 2 cells with a line - coloring the path cell by cell. Even if it's a lame solution it still works fine. But! The line is asymmetric.
As you can see the upper part has 2-cell lines but the bottom one has 3-cell lines. And it looks assymetric. I want it to add 3-cell lines in the middle of the connecting line or near the ends of the connecting line. How do I do that? Or maybe what is the better solution for connecting cells?
Cause you also asked for other solutions, this is one (based on my comment, which I wonder if it really would work (dind't manage to do it with only CSS though)) but to give you an idea here's an example using javascript and CSS ...
var rows = document.querySelectorAll('table tr');
var styleElement = document.createElement('style');
var styles = '';
rows.forEach((element, index) => {
var rowNr = (index +1);
var cellNr = (index+index +1);
styles = styles + 'tr:nth-child('+rowNr+') td:nth-child('+cellNr+'),tr:nth-child('+rowNr+') td:nth-child('+(cellNr+1)+') { background: red;}'
});
styleElement.innerHTML = styles;
document.body.appendChild(styleElement);
table {
border-collapse: collapse;
}
td {
border: solid 1px gray;
width: 20px;
height: 20px;
}
/* unfortunately this didn't work but shows the logic needed */
/*
tr:nth-child(1) td:nth-child(1),
tr:nth-child(1) td:nth-child(2) {
background: red;
}
tr:nth-child(2) td:nth-child(3),
tr:nth-child(2) td:nth-child(4) {
background: blue;
}
*/
<table>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td>
</tr>
</table>
If you want to play with it here is a fiddle
trying to calculate time difference between two input time for dynamically cloned table row. but the JavaScript is only showing the time difference for the very first row. rest are not calculating automatically.
i have tried defining the class for it. still not working
function cloneRow() {
var row = document.getElementById("rowToClone");
var table = document.getElementById("dataTable");
var tags = table.getElementsByTagName('tr');
var len = tags.length;
var clone = row.cloneNode(true);
clone.id = "row_" + len;
clone.id = "newID";
table.appendChild(clone);
}
function deleteRow(tableID) {
try {
var table =
document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
function pad(num) {
return ("0" + num).slice(-2);
}
function diffTime(start, end) {
var s = start.split(":"),
sMin = +s[1] + s[0] * 60,
e = end.split(":"),
eMin = +e[1] + e[0] * 60,
diff = eMin - sMin;
if (diff < 0) {
sMin -= 24 * 60;
diff = eMin - sMin
}
var h = Math.floor(diff / 60),
m = diff % 60;
return "" + pad(h) + " hrs:" + pad(m) + " min";
}
function change() {
window.document.getElementById('delay').value = diffTime(
window.document.getElementById('timeOfCall').value,
window.document.getElementById('timeOfResponse').value
);
}
<INPUT type="button" value="Add Row" onclick="cloneRow()" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<br><br>
<table id="dataTable" border=1>
<tr>
<th></th>
<th>Start Time</th>
<th>End Time</th>
<th>Duration</th>
</tr>
<tr id="rowToClone">
<TD>
<INPUT type="checkbox" name="chk" />
</TD>
<td><input type="datetime" name="stime" placeholder="hrs:mins" value="hh:mm" id="timeOfCall"></td>
<td><input type="datetime" name="etime" placeholder="hrs:mins" value="hh:mm" id="timeOfResponse"></td>
<td><input type="text" id="delay" class="value" onclick="change(this.value)"> </td>
</tr>
</table>
want to auto calculate the time for the particular row when clicked on the duration box of the respective row
Supposed that I have a table like this on a webpage with the id ='table':
Name Age Money(USD) DATE
A 19 4 2019-03-11 16:15:35
B 20 0 2019-03-11 16:16:37
C 27 3 2019-03-13 04:15:43
D 34 0 2019-03-13 04:16:57
Could you help me find the FIRST SMALLEST VALUE IN THE MONEY COLUMN, which is 0 for B in the Column1 and HIGHLIGHT the whole table row for B, using javascript without using any library and any button onClicking?
Note: I have searched around and just been unlucky enough to find the correct answer to my problem.
Thanks.
UPDATE:I just got a piece of javacript like this to get the first smallest value and print it out, but not be able to highlight the whole row with it
var table = document.getElementById("table"), minVal;
for(var i = 1; i < table.rows.length; i++)
{
// if its the first row get the value
if(i === 1){minVal = table.rows[i].cells[2].innerHTML; }
// test with the other values
else if(minVal > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2].innerHTML;
}
}
document.getElementById("val").innerHTML = " Minimum Value = "+minVal;
console.log(maxVal);
var table = document.getElementById("table"), minVal, minI;
for(var i = 1; i < table.rows.length; i++){
if(i === 1){
minVal = table.rows[i].cells[2].innerHTML;
}
else if(minVal > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2].innerHTML;
minI = i;
}
}
table.rows[i].cells[2].innerHTML = '<span style="background:red">' + table.rows[minI].cells[2].innerHTML + '</span>';
Something like that.
var table = document.getElementById("table");
var minVal = undefined;
for(var i = 1; i < table.rows.length; i++)
{
if(i === 1){
minVal = table.rows[i].cells[2];
}
else if(minVal.innerHTML > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2];
}
}
minVal.parentElement.style.background="yellow";
There are two things you need to do:
Convert innerHTML to a number using +
Keep track of the row number while looping.
This is the code
var table = document.getElementById("table"), minVal;
let minRow = 1;
for(var i = 1; i < table.rows.length; i++)
{
// if its the first row get the value
if(i === 1){
minVal = +table.rows[i].cells[2].innerHTML;
}
// test with the other values
else if(minVal > table.rows[i].cells[2].innerHTML){
minVal = table.rows[i].cells[2].innerHTML;
minRow = i;
}
}
let row = table.rows[minRow];
row.style.backgroundColor = 'red';
This simply keeps track of the minimum row, and lets you hang your formatting off of that:
const highlightLowest = () => {
var rows = table.rows;
var minRow = rows[0]
for (var i = 1; i < rows.length; i++){
rows[i].classList.remove('highlight')
if (Number(rows[i].cells[2].innerHTML) < Number(minRow.cells[2].innerHTML)) {
minRow = rows[i]
}
}
minRow.classList.add('highlight')
}
tr.highlight td {background-color: yellow}
<table id="table">
<tr><td>A</td><td>19</td><td>4</td><td>2019-03-11 16:15:35</td></tr>
<tr><td>B</td><td>20</td><td>0</td><td>2019-03-11 16:16:37</td></tr>
<tr><td>C</td><td>27</td><td>3</td><td>2019-03-13 04:15:43</td></tr>
<tr><td>D</td><td>34</td><td>0</td><td>2019-03-13 04:16:57</td></tr>
</table>
<hr />
<button onClick="highlightLowest()">Highlight</button>
Here you go. The function 'highlight' takes the column that you want to base your highlighting upon as an argument.
// Get your table's headers
headers = document.querySelectorAll('#table tbody tr th')
// Get your table's headers
rows = document.querySelectorAll('#table tbody tr')
// Declaring function that takes wanted column as argument
highlight = (colName) =>{
let min = 0;
for(i=0;i<headers.length;i++){
if(headers[i].innerText == colName){
for(j=1;j<rows.length;j++){
value = parseInt(rows[j].children[i].innerHTML);
if(j == 1){
min = value;
}
if(value < min){
rows[j].style.backgroundColor = "yellow"
break;
}
}
}
}
}
<table id="table">
<tbody><tr>
<th>Test 1</th>
<th>Test 2</th>
<th>Test 3</th>
</tr>
<tr>
<td>7</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>3</td>
<td>5</td>
<td>5</td>
</tr>
<tr>
<td>12</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>15</td>
<td>89</td>
<td>4</td>
</tr>
<tr>
<td>3</td>
<td>6</td>
<td>6</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>8</td>
</tr>
</tbody></table>
<input type='text' id='col'>
<button onclick=highlight(document.getElementById('col').value)>Highlight based on input column</button>
I have created a dynamic table based on user input and selecting the cells using jquery. Now i want to merge the selected cells using jquery.
Thanks, Regards.
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.border = '1';
table.id = 'myTable';
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
$(document).ready(function () {
$('#myTable td').click(function () {
var selected = $(this).hasClass('highlited');
$('#myTable tr').removeClass('highlited');
if (!selected)
$(this).addClass('highlited');
});
});
});
}
UI :
on clicking the merge button selected cells should be merged.
You want to highlight TD after dynamically created.
Part 1:
Step 1 : Create dynamically table
Step 2 : Apply click event to each td
Part 2:
Merge td who has highlited class in each tr;
Please check below code:
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.border = '1';
table.id = 'myTable';
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Click me, Row:" + rowCtr + " Column:" + cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
$('#myTable td').each(function () {
$(this).click(function () {
var selected = $(this).hasClass('highlited');
$('#myTable tr').removeClass('highlited');
if (!selected) $(this).addClass('highlited');
});
});
};
function mergeCell() {
$('#myTable tr').each(function (e) {
var oldTDLength = $(this).find('td').length;
for(xTD=0; xTD<oldTDLength;xTD++)
{
crrTD = $(this).find('td:eq(' + xTD + ')');
crrTDNext = $(this).find('td:eq(' + xTD + ')').next();
var colSpan = 1;
while (((crrTD.hasClass('highlited')) && (crrTD.hasClass('highlited') == crrTDNext.hasClass('highlited')))) {
var tempCell = crrTDNext;///store old cell in temp
crrTDNext = crrTDNext.next();///get next
tempCell.remove();///remove next highlited cell
colSpan++;
xTD++;//to skip merged cell
}
if (colSpan > 1) crrTD.attr('colSpan', colSpan);
}//td loop
});//tr loop
}
.highlited{background-color:#ffd800;color:#ff0000}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Row Count</td>
<td>Column Count</td>
<td></td>
</tr>
<tr>
<td><input type="text" id="txtrows" value="5" /></td>
<td><input type="text" id="txtcols" value="5" /></td>
<td><button onclick="CreateTable()">Create Table</button></td>
</tr>
</table>
<div id="myDynamicTable"></div>
<button onclick="mergeCell()">Merge Highlight Cell</button>
var StartTD = null;
var StartIndex = null;
var EndTD = null;
var EndIndex = null;
$().ready(function() {
$("td").unbind("mousedown").bind("mousedown", function() {
$("table td").css("background-color", "");
StartTD = $(this);
var y = $(this).index();
var x = $(this).parent().index();
StartIndex = {
x: x,
y: y
};
});
$("td").unbind("mouseup").bind("mouseup", function() {
EndTD = $(this);
var y = $(this).index();
var x = $(this).parent().index();
EndIndex = {
x: x,
y: y
};
SelectTD(StartIndex, EndIndex, "green");
});
$("#btMerge").click(function() {
MergeCell(StartIndex, EndIndex);
MergeCell(EndIndex, StartIndex);
});
});
function SelectTD(StartIndex, EndIndex, Color) {
var MinX = null;
var MaxX = null;
var MinY = null;
var MaxY = null;
if (StartIndex.x < EndIndex.x) {
MinX = StartIndex.x;
MaxX = EndIndex.x;
} else {
MinX = EndIndex.x;
MaxX = StartIndex.x;
};
if (StartIndex.y < EndIndex.y) {
MinY = StartIndex.y;
MaxY = EndIndex.y;
} else {
MinY = EndIndex.y;
MaxY = StartIndex.y;
};
StartIndex = {
x: MinX,
y: MinY
};
EndIndex = {
x: MaxX,
y: MaxY
};
for (var i = MinX; i <= MaxX; i++) {
for (var j = MinY; j <= MaxY; j++) {
var SelectTR = $("table tr").eq(i);
$("td", SelectTR).eq(j).css("background-color", Color);
}
}
}
function MergeCell(StartIndex, EndIndex) {
var Colspan = null;
var Rowspan = null;
console.log(StartIndex, EndIndex)
Rowspan = EndIndex.x - StartIndex.x + 1;
Colspan = EndIndex.y - StartIndex.y + 1;
var IndexTR = $("table tr").eq(StartIndex.x);
$("td", IndexTR).eq(StartIndex.y).attr("colspan", Colspan).attr("rowspan",
Rowspan);
for (var i = StartIndex.x; i <= EndIndex.x; i++) {
for (var j = StartIndex.y; j <= EndIndex.y; j++) {
if (i == StartIndex.x && j == StartIndex.y) continue;
var SelectTR = $("table tr").eq(i);
$("td", SelectTR).eq(j).hide();
}
}
}
table {
width: 80%;
}
table td {
border: 1px solid #97B4D1;
text-align: center;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</table>
<input id="btMerge" type="button" value="Merge cells" />
Is there any way to find the highest value of each column (in a html table) and to add a class to it using js or jQuery?
Note: the table is build with <thead> and <tbody>
The table looks like this:
<table>
<thead>
<tr>
<th class="age">age</th>
<th class="success">success</th>
<th class="weight">weight</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>30%</td>
<td>70.5kg</td>
</tr>
<tr>
<td>30</td>
<td>40%</td>
<td>80.9kg</td>
</tr>
<tr>
<td>13</td>
<td>60%</td>
<td>20.53kg</td>
</tr>
<tr>
<td>44</td>
<td>80.44%</td>
<td>20kg</td>
</tr>
</tbody>
</table>
Codepen
FIDDLE - http://jsfiddle.net/tariqulazam/esfj9/
JAVASCRIPT
var $table = $("#mytable");
$table.find("th").each(function(columnIndex)
{
var oldValue=0, currentValue=0, $elementToMark;
var $trs = $table.find("tr");
$trs.each(function(index, element)
{
$(this).find("td:eq("+ columnIndex +")").each(function()
{
if(currentValue>oldValue)
oldValue = currentValue;
currentValue = parseFloat($(this).html());
if(currentValue > oldValue)
{
$elementToMark = $(this);
}
if(index == $trs.length-1)
{
$elementToMark.addClass("highest");
}
});
});
});
CSS
.highest{
color:Red;
}
Here's the JSFiddle I made:JSFiddle
Here's the function, using jQuery
function MarkLargest() {
var colCount = $('th').length;
var rowCount = $('tbody tr').length;
var largestVals = new Array();
for (var c = 0; c < colCount; c++) {
var values = new Array();
for (var r = 0; r < rowCount; r++) {
var value = $('tbody tr:eq(' + r + ') td:eq(' + c + ')').text();
value = value.replace("%", "").replace("kg", "");
values.push(value);
}
var largest = Math.max.apply(Math, values);
largestVals.push(largest);
$('tbody tr').each(function() {
var text = $(this).find('td:eq(' + c + ')').text();
text = text.replace("%", "").replace("kg", "");
if (text == largest) {
$(this).find('td:eq(' + c + ')').addClass("max");
}
});
}
return largestVals[column];
}
$(function() {
MarkLargest();
})
OK, my first answer only returned the highest value of a particular column. I think this is what you are looking for (in vanilla JavaScript):
HTML
<table id="mytable">
<thead>
<tr>
<th class="age">age</th>
<th class="sucess">sucess</th>
<th class="weight">weight</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>30%</td>
<td>70.5kg</td>
</tr>
<tr>
<td>30</td>
<td>40%</td>
<td>80.9kg</td>
</tr>
<tr>
<td>13</td>
<td>60%</td>
<td>20.53kg</td>
</tr>
<tr>
<td>44</td>
<td>80.44%</td>
<td>20kg</td>
</tr>
</tbody>
</table>
JavaScript
function markColumnCeilings ( table ) {
if ( table === null ) return;
var thead = table.tHead,
tbody = table.tBodies[0],
rowCount = tbody.rows.length,
colCount = thead.rows[0].cells.length,
maxvalues = new Array( colCount ),
maxCells = new Array( colCount ),
i = rowCount - 1,
j = colCount - 1,
cell, value;
// Loops through rows/columns to get col ceilings
for ( ; i > -1 ; i-- ) {
for ( ; j > -1 ; j-- ) {
cell = tbody.rows[ i ].cells[ j ];
value = parseFloat( cell.innerHTML );
if ( value.toString() === "NaN" ) continue;
if ( value > ( maxvalues[ j ] === undefined ? -1 : maxvalues[ j ] ) ) {
maxvalues[ j ] = value;
maxCells[ j ] = i + "," + j;
}
}
j = colCount - 1;
}
// Set classes
for ( ; j > -1 ; j-- ) {
tbody.rows[ maxCells[ j ].split( "," )[ 0 ] ]
.cells[ maxCells[ j ].split( "," )[ 1 ] ]
.setAttribute( "class", "max" );
}
}
var table = document.getElementById( 'mytable' );
markColumnCeilings( table );
CSS
td.max { font-weight: bold; }
Fiddle: http://jsfiddle.net/kboucher/cH8Ya/
I have modified the function of #sbonkosky to be able to manage various tables. In my case I have various tables and it was mixing values of all them.
function GetLargestValueForColumn(table) {
let colCount = $('table:eq('+ table +') th').length;
let rowCount = $('table:eq('+ table +') tbody tr').length;
let largestVals = new Array();
for (let c = 0; c < colCount; c++) {
let values = new Array();
for (let r = 0; r < rowCount; r++) {
let value = $('table:eq('+ table +') tbody tr:eq(' + r + ') td:eq(' + c + ')').text();
value = value.replace("%", "").replace("kg", "").replace(" ", "").replace(".", "");
values.push(value);
}
let largest = Math.max.apply(Math, values);
largestVals.push(largest);
$('tbody tr').each(function() {
let text = $(this).find('td:eq(' + c + ')').text();
text = text.replace("%", "").replace("kg", "").replace(" ", "").replace(".", "");
if (text == largest) {
$(this).find('td:eq(' + c + ')').addClass("max");
}
});
}
return
}
$(function() {
$('table').each(function(table) {GetLargestValueForColumn(table)});
})