Grouping table rows based on cell value using jquery/javascript - javascript

I have been trying to solve this for days.I would greatly appreciate any help you can give me in solving this problem. I have a table like the following:
ID Name Study
1111 Angela XRAY
2222 Bena Ultrasound
3333 Luis CT Scan
1111 Angela Ultrasound
3333 Luis XRAY
3333 Luis LASER
and I want to group them like:
ID Name Study
GROUP BY id(1111) 2 hits "+"
2222 Bena Ultrasound
GROUP BY id(3333) 3 hits "+"
AND if "+" is clicked then it will expand:
ID Name Study
GROUP BY id(1111) 2 hits "-"
1111 Angela XRAY
1111 Angela Ultrasound
2222 Bena Ultrasound
GROUP BY id(3333) 3 hits "-"
3333 Luis CT Scan
3333 Luis Ultrasound
3333 Luis LASER
There is a demo that I found on stackoverflow(http://jsfiddle.net/FNvsQ/1/) but the only problem I have is I want to include all rows having the same id under a dynamic header like
grouped by id(1111) then the expand/collapse icon (+/-)
var table = $('table')[0];
var rowGroups = {};
//loop through the rows excluding the first row (the header row)
while(table.rows.length > 0){
var row = table.rows[0];
var id = $(row.cells[0]).text();
if(!rowGroups[id]) rowGroups[id] = [];
if(rowGroups[id].length > 0){
row.className = 'subrow';
$(row).slideUp();
}
rowGroups[id].push(row);
table.deleteRow(0);
}
//loop through the row groups to build the new table content
for(var id in rowGroups){
var group = rowGroups[id];
for(var j = 0; j < group.length; j++){
var row = group[j];
if(group.length > 1 && j == 0) {
//add + button
var lastCell = row.cells[row.cells.length - 1];
$("<span class='collapsed'>").appendTo(lastCell).click(plusClick);
}
table.tBodies[0].appendChild(row);
}
}
//function handling button click
function plusClick(e){
var collapsed = $(this).hasClass('collapsed');
var fontSize = collapsed ? 14 : 0;
$(this).closest('tr').nextUntil(':not(.subrow)').slideToggle(400)
.css('font-size', fontSize);
$(this).toggleClass('collapsed');
}

Here is the answer to my own question.
First id's are added to the table and the rows and there's a small change to the JS:
var table = $('table')[0];
var rowGroups = {};
//loop through the rows excluding the first row (the header row)
while (table.rows.length > 1) {
var row = table.rows[1];
var id = $(row.cells[0]).text();
if (!rowGroups[id]) rowGroups[id] = [];
if (rowGroups[id].length > 0) {
row.className = 'subrow';
$(row).slideUp();
}
rowGroups[id].push(row);
table.deleteRow(1);
}
//loop through the row groups to build the new table content
for (var id in rowGroups) {
var group = rowGroups[id];
for (var j = 0; j < group.length; j++) {
var row = group[j];
var notSubrow = false;
if (group.length > 1 && j == 0) {
//add + button
var lastCell = row.cells[row.cells.length - 1];
var rowId = row.id;
var tableId = table.id;
notSubrow = true;
//$("<span class='collapsed'>").appendTo(lastCell).click(plusClick);
}
table.tBodies[0].appendChild(row);
if (notSubrow) {
$('#' + tableId).find('#' + rowId).attr('class', 'subrow');
$('#' + tableId).find('#' + rowId).before("<tr class='subrowHeader' style='background:#E6E6FA;border-bottom:1px solid #708AA0 !important'><td colspan='3'> group by&nbsp" + $(row.cells[0]).text() + " (" + group.length + ")" + "<span class='collapsed' onclick='plusClick(this)' style='float:left;display:inline'></td></tr>");
$('#' + tableId).find('#' + rowId).hide();
}
}
}
//function handling button click
function plusClick(e) {
var collapsed = $(e).hasClass('collapsed');
var fontSize = collapsed ? 14 : 0;
$(e).closest('tr').nextUntil(':not(.subrow)').slideToggle('fast').css('font-size', fontSize);
$(e).toggleClass('collapsed');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table1">
<tr id="tr1">
<th>Parent ID</th>
<th>Parent Name</th>
<th>Study</th>
</tr>
<tr id="tr2">
<td>1111</td>
<td>Angela</td>
<td>XRAY</td>
</tr>
<tr id="tr3">
<td>2222</td>
<td>Bena</td>
<td>Untrasound</td>
</tr>
<tr id="tr4">
<td>3333</td>
<td>Luis</td>
<td>CT Scan</td>
</tr>
<tr id="tr5">
<td>1111</td>
<td>Angela</td>
<td>Untrasound</td>
</tr>
<tr id="tr6">
<td>3333</td>
<td>Luis</td>
<td>LCD</td>
</tr>
<tr id="tr7">
<td>3333</td>
<td>Luis</td>
<td>LASER</td>
</tr>
</table>
*Inorder to test copy and paste the code into http://jsfiddle.net/FNvsQ/1/ &
In the Frameworks & Extensions panel, set onLoad to No wrap - in body.

As a comparison, here's a POJS function that is functionally equivalent in the same amount of code. Doesn't use a large external library though.
It uses the same algorithm of collecting all rows with the same value in the first cell, then modifies the table to insert header rows and group the data rows.
// Group table rows by first cell value. Assume first row is header row
function groupByFirst(table) {
// Add expand/collapse button
function addButton(cell) {
var button = cell.appendChild(document.createElement('button'));
button.className = 'toggleButton';
button.textContent = '+';
button.addEventListener('click', toggleHidden, false);
return button;
}
// Expand/collapse all rows below this one until next header reached
function toggleHidden(evt) {
var row = this.parentNode.parentNode.nextSibling;
while (row && !row.classList.contains('groupHeader')) {
row.classList.toggle('hiddenRow');
row = row.nextSibling;
}
}
// Use tBody to avoid Safari bug (appends rows to table outside tbody)
var tbody = table.tBodies[0];
// Get rows as an array, exclude first row
var rows = Array.from(tbody.rows).slice(1);
// Group rows in object using first cell value
var groups = rows.reduce(function(groups, row) {
var val = row.cells[0].textContent;
if (!groups[val]) groups[val] = [];
groups[val].push(row);
return groups;
}, Object.create(null));
// Put rows in table with extra header row for each group
Object.keys(groups).forEach(function(value, i) {
// Add header row
var row = tbody.insertRow();
row.className = 'groupHeader';
var cell = row.appendChild(document.createElement('td'));
cell.colSpan = groups[value][0].cells.length;
cell.appendChild(
document.createTextNode(
'Grouped by ' + table.rows[0].cells[0].textContent +
' (' + value + ') ' + groups[value].length + ' hits'
)
);
var button = addButton(cell);
// Put the group's rows in tbody after header
groups[value].forEach(function(row){tbody.appendChild(row)});
// Call listener to collapse group
button.click();
});
}
window.onload = function(){
groupByFirst(document.getElementById('table1'));
}
table {
border-collapse: collapse;
border-left: 1px solid #bbbbbb;
border-top: 1px solid #bbbbbb;
}
th, td {
border-right: 1px solid #bbbbbb;
border-bottom: 1px solid #bbbbbb;
}
.toggleButton {
float: right;
}
.hiddenRow {
display: none;
}
<table id="table1">
<tr id="tr1">
<th>Parent ID</th>
<th>Parent Name</th>
<th>Study</th>
</tr>
<tr id="tr2">
<td>1111</td>
<td>Angela</td>
<td>XRAY</td>
</tr>
<tr id="tr3">
<td>2222</td>
<td>Bena</td>
<td>Ultrasound</td>
</tr>
<tr id="tr4">
<td>3333</td>
<td>Luis</td>
<td>CT Scan</td>
</tr>
<tr id="tr5">
<td>1111</td>
<td>Angela</td>
<td>Ultrasound</td>
</tr>
<tr id="tr6">
<td>3333</td>
<td>Luis</td>
<td>LCD</td>
</tr>
<tr id="tr7">
<td>3333</td>
<td>Luis</td>
<td>LASER</td>
</tr>
</table>

Related

How to auto increament serial number of row in html using Javascript

I am trying to add rows of tables. I can't add serial number of new added rows.
i.e. I have to show serial number automatic increment while row is added.
<SCRIPT language="javascript">
function addRow(dataTable) {
var table = document.getElementById('dataTable');
var rowCount = table.rows.length;
var row = table.insertRow(2);
var colCount = table.rows[3].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[3].cells[i].innerHTML;
}
</SCRIPT>
Any idea? plz help
addCells(table, rows, cells);
table: A string that represents the id of the targeted table.
Ex. addCells('dataTable',...)
rows: An integer of the quantity of rows to be appended to target tabel.
Ex. addCells('dataTable', 4, ...)
cells: An integer of how many cells per row.
Ex. addCells('dataTable', 4, 5)
Each row and cell is assigned a unique id, this is the pattern:
Row: table id+R+row position
Ex. #dataTableR3 = 4th row of #dataTable
Cell: table id+R+row position+C+cell position
Ex. #dataTableR3C7 = 8th cell of 4th row of #dataTable
Note the offset in the numbers. This is due to the fact that the id system is 0-count (starts with 0 as the first number.) Check the dev tools - console to see all of the generated ids.
Here's the jQuery version, from this similar question. I don't consider it a duplicate since your question is more specific about an aspect of that previously mentioned question.
var btn1 = document.getElementById('btn1');
btn1.addEventListener('click', function(e) {
var inp0 = document.getElementById('inp0').value;
var inp1 = document.getElementById('inp1').value;
var inp2 = document.getElementById('inp2').value;
addCells(inp0, inp1, inp2);
}, false);
function addCells(table, rows, cells) {
var T = document.getElementById(table);
var R = parseInt(rows);
var C = parseInt(cells);
for (var i = 0; i < R; i++) {
var row = document.createElement('tr');
T.appendChild(row);
row.setAttribute('id', table + 'R' + i);
console.log('Appended row: ' + table + 'R' + i);
for (var j = 0; j < C; j++) {
var cell = document.createElement('td');
row.appendChild(cell)
cell.setAttribute('id', table + 'R' + i + 'C' + j);
console.log('Appended cell: ' + table + 'R' + i + 'C' + j);
}
}
}
fieldset {
margin: 20px;
}
table {
border: 3px double blue;
table-layout: fixed;
}
td {
border: 1px solid red;
width: 20px;
height: 20px
}
<fieldset>
<legend>Enter Table ID, Number of Rows, & Number of Cells per Row</legend>
<label for="inp0">Table</label>
<input id="inp0" />
<br/>
<label for="inp1">Rows</label>
<input id="inp1" />
<br/>
<label for="inp2">Cells</label>
<input id="inp2" />
<br/>
<button id="btn1">Enter</button>
</fieldset>
<table id="t">
<tr>
<td>Table</td>
<td>ID</td>
<td>is</td>
<td>t</td>
<td> </td>
</tr>
</table>
<table id="u">
<caption>Table ID: u</caption>
</table>

jQuery/Javascript compare two tables against each other

I need to compare two HTML tables' rows assuming that data in first cell can be duplicated but data in second cell is always unique. I need to find whether first cell AND second cell in table1 is the same as data in first cell AND second cell in table2 for instance:
Table1:
<Table>
<tr>
<td>123</td>
<td>321</td>
</tr>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>0</td>
<td>312</td>
</tr>
<tr>
<td>123</td>
<td>323331</td>
</tr>
</Table>
Second table:
<table>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>545</td>
<td>3122</td>
</tr>
<tr>
<td>123</td>
<td>321</td>
</tr>
</table>
The result of this should be:
123 321 - good, do nothing
545 345 - good, do nothing
545 3122 - wrong its not in table1 <-
Here's what I've got so far...
$('#runCheck').click(function(){
var firstTable = $('#firstDiv table tr');
var secondTable = $('#secDiv table tr');
$(secondTable).each(function(index){
var $row = $(this);
var secTableCellZero = $row.find('td')[0].innerHTML;
var secTableCellOne = $row.find('td')[1].innerHTML;
$(firstTable).each(function(indexT){
if ($(this).find('td')[0].innerHTML === secTableCellZero){
if ($(this).find('td')[1].innerHTML !== secTableCellOne){
$('#thirdDiv').append("first: " + secTableCellZero + " second: " + secTableCellOne+"<br>");
}
}
});
});
});
Where am I going it wrong?
Just to clarify once again:
2nd table says :
row1 - john|likesCookies
row2 - peter|likesOranges
1st table says :
row1 - john|likesNothing
row2 - john|likesCookies
row3 - steward|likesToTalk
row4 - peter|likesApples
now it should say :
john - value okay
peter - value fail.
a lot alike =VLOOKUP in excel
Check this working fiddle : here
I've created two arrays which store values in each row of tables 1 and 2 as strings. Then I just compare these two arrays and see if each value in array1 has a match in array 2 using a flag variable.
Snippet :
$(document).ready(function() {
var table_one = [];
var table_two = [];
$("#one tr").each(function() {
var temp_string = "";
count = 1;
$(this).find("td").each(function() {
if (count == 2) {
temp_string += "/";
}
temp_string = temp_string + $(this).text();
count++;
});
table_one.push(temp_string);
});
$("#two tr").each(function() {
var temp_string = "";
count = 1;
$(this).find("td").each(function() {
if (count == 2) {
temp_string += "/";
temp_string = temp_string + $(this).text();
} else {
temp_string = temp_string + $(this).text();
}
count++;
});
table_two.push(temp_string);
});
var message = "";
for (i = 0; i < table_two.length; i++) {
var flag = 0;
var temp = 0;
table_two_entry = table_two[i].split("/");
table_two_cell_one = table_two_entry[0];
table_two_cell_two = table_two_entry[1];
for (j = 0; j < table_one.length; j++) {
table_one_entry = table_one[j].split("/");
table_one_cell_one = table_one_entry[0];
table_one_cell_two = table_one_entry[1];
console.log("1)" + table_one_cell_one + ":" + table_one_cell_two);
if (table_two_cell_one == table_one_cell_one) {
flag++;
if (table_one_cell_two == table_two_cell_two) {
flag++;
break;
} else {
temp = table_one_cell_two;
}
} else {}
}
if (flag == 2) {
message += table_two_cell_one + " " + table_two_cell_two + " found in first table<br>";
} else if (flag == 1) {
message += table_two_cell_one + " bad - first table has " + temp + "<br>";
} else if (flag == 0) {
message += table_two_cell_one + " not found in first table<br>";
}
}
$('#message').html(message);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="one">
<tr>
<td>123</td>
<td>321</td>
</tr>
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>0</td>
<td>312</td>
</tr>
<tr>
<td>123</td>
<td>323331</td>
</tr>
</table>
<hr>
<table id="two">
<tr>
<td>545</td>
<td>345</td>
</tr>
<tr>
<td>545</td>
<td>3122</td>
</tr>
<tr>
<td>123</td>
<td>321</td>
</tr>
</table>
<hr>
<div id="message">
</div>
</div>
If I understand your requirements, it would be easier to read the first table and store the couples as strings: 123/321, 545/345, etc...
Than you can read the second table and remove from the first list all the rows found in both.
What remains in the list are couples that do not match.
From purely an efficiency standpoint if you loop through the first table just once and create an object using the first cell value as keys and an array of values for second cells, you won't have to loop through that table numerous times
this then makes the lookup simpler also
var firstTable = $('#firstDiv table tr');
var secondTable = $('#secDiv table tr');
var firstTableData = {}
firstTable.each(function() {
var $tds = $(this).find('td'),
firstCellData = $tds.eq(0).html().trim(),
secondCellData == $tds.eq(1).html().trim();
if (!firstTableData[firstCellData]) {
firstTableData[firstCellData] = []
}
firstTableData[firstCellData].push(secondCellData)
})
$(secondTable).each(function(index) {
var $tds = $(this).find('td');
var secTableCellZero = $tds.eq(0).html().trim();
var secTableCellOne = $tds.eq(1).html().trim();
if (!firstTableData.hasOwnProperty(secTableCellZero)) {
console.log('No match for first cell')
} else if (!firstTableData[secTableCellZero].indexOf(secTableCellOne) == -1) {
console.log('No match for second cell')
}
});
I'm not sure what objective is when matches aren't found

Getting coordinates of table cells and comparing with different tables via Javascript

It's really easy to access to coordinates of table cells with this and this example ways. But when I'm trying to get cells and compare with another table's cell which is avaible on page, a problem occurs. Because I don't know how to compare them in same time. After many hours I tried to do this, unfortunately, still there is no luck.
In following classic tables list below, shows 2 different tables with different id numbers:
<table id="a1">
<tbody>
<tr>
<td>RED</td>
<td>GREEN</td>
<td>BLUE</td>
</tr>
<tr>
<td>YELLOW</td>
<td>PINK</td>
<td>samespothere</td>
</tr>
</tbody>
</table>
<hr>
<table id="a2">
<tbody>
<tr>
<td>BLACK</td>
<td>BROWN</td>
<td>WHITE</td>
</tr>
<tr>
<td>CYAN</td>
<td>GRAY</td>
<td>samespothereANDsomeextra</td>
</tr>
</tbody>
</table>
And also, I'm using modified version of this JS example to get location of cells. This modified version I did is not able to make compare operation. I've just edited for make it easier.
var cells = document.getElementsByTagName("td"); //For all table cells on page.
var i;
for(i = 0; i < cells.length; i++)
{
cells[i].onclick = vera;
}
function vera()
{
var cellIndex = this.cellIndex + 1;
var rowIndex = this.parentNode.rowIndex + 1;
var centra = cellIndex +","+ rowIndex; //This gives the coordinate of cell which you clicked on.
alert(centra);
}
Here is my question: I need to make a compare operation when I click on samespothere(Example text I wrote) table cell. Compare operation should be able with the same location of other table. Lets think like this: If second table cell(same location, different table) includes some of clicked cell's text(from first table), alert must show up and say "This clicked text in table id=1 cell:2row:2, matched in table id=2 cell:2row:2".
And here is the online code: http://jsfiddle.net/LujydnaL/
I think this is what you want:
function vera()
{
var cellIndex = this.cellIndex + 1;
var rowIndex = this.parentNode.rowIndex + 1;
var centra = cellIndex +","+ rowIndex; //This gives the coordinate of cell which you clicked on.
alert(centra);
// new code here
table2 = document.getElementById('a2');
rowInTable2 = table2.getElementsByTagName('tr')[rowIndex-1];
cellInTable2 = rowInTable2.getElementsByTagName('td')[cellIndex-1];
console.log(cellInTable2);
// do something with cellInTable2 now
}
window.onload = function () {
document.getElementsByTagName('table')[0].addEventListener('click', function(element) {
var rowIndex = element.target.parentElement.rowIndex;
var cellIndex = element.target.cellIndex;
var compare = document.getElementsByTagName('table')[1].rows[rowIndex].cells[cellIndex];
var myNodelist = document.querySelectorAll("td");
var i;
for (i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.backgroundColor = "white";
}
compare.style.backgroundColor = "grey";
document.getElementById('alert1').innerHTML = ('CLICK => Row index = ' + rowIndex + ', Column index = ' + cellIndex);
document.getElementById('alert2').innerHTML = ('COMPARE = ' + compare.innerHTML)
}, false);
}
tr, th, td {
padding: 0.2rem;
border: 1px solid black
}
table:hover {
cursor: pointer;
}
<table>
<tbody>
<tr>
<td>a11</td>
<td>a12</td>
<td>a13</td>
</tr>
<tr>
<td>a21</td>
<td>a22</td>
<td>a23</td>
</tr>
</tbody>
</table>
<p id="alert1"></p>
<hr>
<table>
<tbody>
<tr>
<td>b11</td>
<td>b12</td>
<td>b13</td>
</tr>
<tr>
<td>b21</td>
<td>b22</td>
<td>b23</td>
</tr>
</tbody>
</table>
<p id="alert2"></p>

How do I select rows that correspond to a rowspan?

I have a dynamically generated table that I am trying to change the background color of certain rows in. Sometimes there are rows with rowspans and I cant figure out how to get all of the rows that correspond to the one "row." I've googled my brains out and found this jsfiddle which is pretty close to what i need (in a logic sense)
http://jsfiddle.net/DamianS1987/G2trb/
basically i have something like this:
and I want to be able to highlight full rows at a time like this:
but the only highlighting i can achieve on rowspan rows is this:
Here is my code (different from jsfiddle but essentially same logic)
CSS:
.highlightedClass{
background-color: #AEAF93;
}
HTML:
<table border="1" class="altTable">
<th>ID</th>
<th>NAME</th>
<th>Miles</th>
<th>WORK</th>
<tbody>
<tr>
<td class="td_id">999B</td>
<td class="td_name ">John</td>
<td class="td_cumMiles">702.4</td>
<td class="td_workEvent">Y</td>
</tr><tr>
<td class="td_id" rowspan="2">111A</td>
<td class="td_name">Tom</td>
<td class="td_cumMiles">446.5</td>
<td class="td_workEvent">Y</td>
</tr><tr>
<td class="td_name">Becky</td>
<td class="td_cumMiles">446.5</td>
<td class="td_workEvent">A</td>
</tr>
</tbody>
JAVASCRIPT:
for(var j=0; j < inspection.length; j++){
var $tr = $('<tr></tr>');
var $td_id = $('<td></td>').addClass('td_id').html(inspection.id);
$tr.append($td_id);
$table.append($tr);
$.each(inspection[i], function(index, value){
var $td_name, $td_miles,$td_workEvent;
if(index > 0){
var $2nd_tr = $('<tr></tr>');
$td_name = $('<td></td>').addClass('td_name').html(value.stationSt);
$td_miles = $('<td></td>').addClass('td_miles').html(value.miles);
$td_workEvent = $('<td></td>').addClass('td_workEvent').html(value.code);
$2nd_tr.append($td_name);
$2nd_tr.append($td_miles);
$2nd_tr.append($td_workEvent);
$table.append($2nd_tr);
$td_id.attr('rowSpan',index+1);
if($td_id.text() === content().id){
$2nd_tr.addClass("highlightedClass");
}else{
if($2nd_tr.hasClass("highlightedClass")){
$2nd_tr.removeClass('highlightedClass');
}
}
$('#workevent').on('click', function(){
$tr.removeClass('highlightedClass');
});
}else{
$td_name = $('<td></td>').addClass('td_name').html(value.stationSt);
$td_miles = $('<td></td>').addClass('td_miles').html(value.miles);
$td_workEvent = $('<td></td>').addClass('td_workEvent').html(value.code);
$tr.append($td_name);
$tr.append($td_miles);
$tr.append($td_workEvent);
$table.append($tr);
if($td_id.text() === content().id){
$tr.addClass("highlightedClass");
}else{
if($tr.hasClass("highlightedClass")){
$tr.removeClass('highlightedClass');
}
}
$('#workevent').on('click', function(){
$tr.removeClass('highlightedClass');
});
}
});
You need to look for any rowspan= attribute in the selected tds and if present, select the subsequent row(s) as well. This example should support any rowspan value (it appends subsequent rows based on the rowspan count):
Final version: JSFiddle: http://jsfiddle.net/TrueBlueAussie/G2trb/22/
$('td').bind('click', function () {
var $row = $(this).closest('tr');
// What row index is the clicked row?
var row = $row.index(); // Subtract heading row
// Does the clicked row overlap anything following?
var rowspan = ~~$row.find('td[rowspan]').attr('rowspan') || 0;
// Get all rows except the heading, up to the last overlapped row
var $rows = $row.parent().children().slice(1, row + rowspan);
row--; // Subtract the heading row we excluded
// Now see if any preceding rows overlap the clicked row
$rows.each(function (i) {
var $tr = $(this);
// Only check first rowspan of a row
var rowspan = ~~$tr.find('td[rowspan]').attr('rowspan') || 0;
// If the rowspan is before the clicked row but overlaps it
// Or it is a row we included after the selection
if ((i < row && ((rowspan + i) > row)) || i > row) {
$row = $row.add($tr);
}
});
$row.toggleClass('green');
});
First attempt JSFiddle: http://jsfiddle.net/TrueBlueAussie/G2trb/18/
$('td').bind('click', function () {
var $td = $(this);
var $row = $td.closest('tr');
var $tds = $row.find('td');
$tds.each(function(){
var rowspan = ~~$(this).attr('rowspan');
while (--rowspan > 0){
$row = $row.add($row.next());
}
});
$row.toggleClass('green');
});
It needs to be tweaked for the child row that sits under a previous rowspan, but am working on that too.
Notes:
~~ is a shortcut to convert a string to an integer.
the || 0 converts undefined values to 0.
$row = $row.add($tr) is appending row elements to a jQuery collection/object.
In fixing my issue (going off what TrueBlueAussie gave me) I came up with the following solution.
CSS:
.highlightedClass{
background-color: #AEAF93;
}
HTML:
<table border="1" class="altTable">
<th>ID</th>
<th>NAME</th>
<th>Miles</th>
<th>WORK</th>
<tbody>
<tr>
<td class="td_id">999B</td>
<td class="td_name ">John</td>
<td class="td_cumMiles">702.4</td>
<td class="td_workEvent">Y</td>
</tr><tr>
<td class="td_id" rowspan="2">111A</td>
<td class="td_name">Tom</td>
<td class="td_cumMiles">446.5</td>
<td class="td_workEvent">Y</td>
</tr><tr>
<td class="td_name">Becky</td>
<td class="td_cumMiles">446.5</td>
<td class="td_workEvent">A</td>
</tr>
</tbody>
JAVASCRIPT:
for(var j=0; j < inspection.length; j++){
var $tr = $('<tr></tr>');
var $td_id = $('<td></td>').addClass('td_id').html(inspection.id);
$tr.append($td_id);
$table.append($tr);
$.each(inspection[i], function(index, value){
var $td_name, $td_miles,$td_workEvent;
if(index > 0){
var $2nd_tr = $('<tr></tr>');
$td_name = $('<td></td>').addClass('td_name').html(value.stationSt);
$td_miles = $('<td></td>').addClass('td_miles').html(value.miles);
$td_workEvent = $('<td></td>').addClass('td_workEvent').html(value.code);
$2nd_tr.append($td_name);
$2nd_tr.append($td_miles);
$2nd_tr.append($td_workEvent);
$table.append($2nd_tr);
$td_id.attr('rowSpan',index+1);
if($td_id.text() === content().td_id){
$2nd_tr.addClass("highlightedClass");
}else{
if($2nd_tr.hasClass("highlightedClass")){
$2nd_tr.removeClass('highlightedClass');
}
}
$('#workevent').on('click', function(){
if($td_id.text() === content().td_id){
$2nd_tr.addClass("highlightedClass");
}else{
if($2nd_tr.hasClass("highlightedClass")){
$2nd_tr.removeClass("highlightedClass");
}
}
});
}else{
$td_name = $('<td></td>').addClass('td_name').html(value.stationSt);
$td_miles = $('<td></td>').addClass('td_miles').html(value.miles);
$td_workEvent = $('<td></td>').addClass('td_workEvent').html(value.code);
$tr.append($td_name);
$tr.append($td_miles);
$tr.append($td_workEvent);
$table.append($tr);
if($td_id.text() === content().id){
$tr.addClass("highlightedClass");
}else{
if($tr.hasClass("highlightedClass")){
$tr.removeClass('highlightedClass');
}
}
}
});
This was in a nested if statement. below like three if statements, i put this:
$('#workevent').on('click', function(){
var flag= false;
$('#altTable > tbody > tr').each(function() {
$td_id= $(this).find('.td_id');
if($td_id.text() === ''){
if(flag === true){
$(this).addClass("highlightedClass");
flag = true;
}
}else{
if(if($td_id.text() === content().idtd_id{){
if($(this).hasClass("highlightedClass")){
flag = true;
}else{
$(this).addClass("highlightedClass");
flag = true;
}
}else{
flag = false;
if($(this).hasClass("highlightedClass")){
$(this).removeClass("highlightedClass");
}
}
}
});
});
This is what worked for me. I selected TrueBlueAussie's answer because it helped get me my specific answer. Hopefully both answers can help someone else in the future.

How to check for duplicate row using javascript

how do I check for duplicate row in a table using javascript? The following is part of my code:
<table id="t1">
<tr>
<td>Text A</td>
<td>Text B</td>
<td>Cbx A</td>
</tr>
<% int count1 = -1;
for(int i=0; i<3; i++) { %>
<tr>
<td><input type="text" id="textA<%=i%>"></td>
<td><input type="text" id="textB<%=i%>"></td>
<td><select name="cbx_A<%=i%>">
<option value="A">Option1</option>
<option value="B">Option2</option>
</select>
</td
</tr>
<%count1 =i;
}%>
<tr>
<td><input type="button" onclick="check(<%=count1%>)" value="Check"></td>
</tr>
</table>
So based on this code, I will have 3 rows of text A,textB and cbxA. With that, how do I check whether user input the same values for 2 of the rows or all three rows?
I tried using servlet but theres too much work involve. So yeah is there a way to do this using java script instead?
Thanks in advance for any possible help.
Using this code it will check for duplication in one table column
then take all rows of table that are duplicated and put their ids in array
so you will get an array of rows id
but ur table has to have an id for each row
var columnNumber = 1;
var table = document.getElementById('t1');
var rowLength = table.rows.length;
var arrReocrds = new Array();
var arrCount = 0;
var listCount = 0;
var arr = new Array();
$('#t1 td:nth-child(' + colNumber + ')').each(function () {
var recordValue = $(this).html().trim();
var flagFirstTime = true;
//loop through table to check redundant of current record value
for (var i = 1; i < rowLength; i += 1) {
{
var row = table.rows[i];
var recordId = //put here row.id or anything that you can put it in the list
var cell = row.cells[colNumber - 1];
var value = cell.innerText.trim();
if (value == recordValue) {
if (!arr.contains(value)) {
if (flagFirstTime != true) {
arrReocrds[arrCount] = recordId;
arrCount++;
}
else
flagFirstTime = false;
}
else
break;
}
}
}
//create list for items in column
//to be sure that the item that has been taken and checked never be checked again by their other redundant records
arr[listCount] = recordValue;
listCount++;
});

Categories

Resources