I'm currently trying to make it so that when the JS code does its thing, the rows with common values and common classes will be merged. The code worked, but all of the common rows were merged without taking into account their classes.
Table code:
<tbody id="property_dtl_table_body">
<% dtls.each do |f| %>
<tr class="<%= payment_paid(f.paid)%>" id="paidrow">
<td>
<% if !f.paid %>
<%= check_box_tag "pin_number[]", f.id, checked= !f.paid? %>
<%end%>
</td>
<td id="pin"><%= f.year %></td>
<td><%= f.quarter %></td>
<td align="right" id="price"><%= number_to_currency(f.amount, unit: "",
precision: 2)%></td>
</tr>
<%end%>
</tbody>
JS Code:
if(!$(this).hasClass('paid')){
var table = $("#property_dtl_table_body");
var rows = table.find($("tr"));
var colsLength = 2;
var removeLater = new Array();
for(var i=1; i<colsLength; i++){
var startIndex = 0;
var lastIndex = 0;
var startText = $($(rows[0]).find("td")[i]).text();
for(var j=1; j<rows.length; j++){
var cRow =$(rows[j]);
if(!$(this).hasClass('paid')){
var cCol = $(cRow.find("td")[i]);
}
var currentText = cCol.text();
if(currentText==startText){
cCol.css("background","gray");
console.log(cCol);
removeLater.push(cCol);
lastIndex=j;
}else{
var spanLength = lastIndex-startIndex;
if(spanLength>=1){
console.log(lastIndex+" - "+startIndex)
//console.log($($(rows[startIndex]).find("td")[i]))
$($(rows[startIndex]).find("td")
[i]).attr("rowspan",spanLength+1);
}
lastIndex = j;
startIndex = j;
startText = currentText;
}
}
var spanLength = lastIndex-startIndex;
if(spanLength>=1){
console.log(lastIndex+" - "+startIndex)
//console.log($($(rows[startIndex]).find("td")[i]))
$($(rows[startIndex]).find("td")
[i]).attr("rowspan",spanLength+1);
}
console.log("---");
}
for(var i in removeLater){
$(removeLater[i]).remove();
}
}
The class in question(#paid) is represented by the green background color as seen here:
Before JS:
After JS:
Expected result:
You can go for the following logic:
Start on the first year td
Loop through the next year td's until you find a different one and count them
When you find one, set the first td's rowspan to the number of elements in between
Remove all those td's that you looped through
Repeat the process until the end
The same classe restriction only applies to the selector that you use to fetch all the tds.
Example:
function mergeByClass(className){
let currTd, count = 0;
$(`tr > .${className}`).each(function(){
if (!currTd) //if its the first one set it as current
currTd = $(this);
else { //if its not
if ($(this).text() == currTd.text()){ //check if its a repeating one
count++; //count if it is
$(this).remove(); //and remove it to properly merge
}
else { //if its a different one
if(count >= 1) //merge if it has 1 or more in between
currTd.attr("rowspan", count + 1);
currTd = $(this); //reset the current one
count = 0;
}
}
});
if (count >= 1) //last element case
currTd.attr("rowspan", count + 1);
}
$("#merge").on("click", () => mergeByClass("paid"));
td {
border: 1px solid black;
padding : 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="merge">Click to merge rows with the same class</button>
<table>
<tr>
<td class="paid">2015</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td class="paid">2015</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td>2016</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td>2016</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td>2017</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td>2017</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td>2017</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td class="paid">2018</td><td>3</td><td>22.97</td>
</tr>
<tr>
<td class="paid">2018</td><td>3</td><td>22.97</td>
</tr>
</table>
Related
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
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 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++;
});
I have a simple HTML table, which uses rowspans in some random columns. An example might look like
A | B |
---|---| C
D | |
---| E |---
F | | G
I'd like to iterate over the rows such that I see rows as A,B,C, D,E,C, then F,E,G.
I think I can probably cobble together something very convoluted using cell.index() to check for "missed" columns in later rows, but I'd like something a little more elegant...
without jquery:
function tableToMatrix(table) {
var M = [];
for (var i = 0; i < table.rows.length; i++) {
var tr = table.rows[i];
M[i] = [];
for (var j = 0, k = 0; j < M[0].length || k < tr.cells.length;) {
var c = (M[i-1]||[])[j];
// first check if there's a continuing cell above with rowSpan
if (c && c.parentNode.rowIndex + c.rowSpan > i) {
M[i].push(...Array.from({length: c.colSpan}, () => c))
j += c.colSpan;
} else if (tr.cells[k]) {
var td = tr.cells[k++];
M[i].push(...Array.from({length: td.colSpan}, () => td));
j += td.colSpan;
}
}
}
return M;
}
var M = tableToMatrix(document.querySelector('table'));
console.table(M.map(r => r.map(c => c.innerText)));
var pre = document.createElement('pre');
pre.innerText = M.map(row => row.map(c => c.innerText).join('\t')).join('\n');
document.body.append(pre);
td {
border: 1px solid rgba(0,0,0,.3);
}
<table>
<tr>
<td colspan=2>A</td>
<td rowspan=2>B</td>
</tr>
<tr>
<td>C</td>
<td rowspan=3>D</td>
</tr>
<tr>
<td rowspan=2>E</td>
<td rowspan=4>F</td>
</tr>
<tr></tr>
<tr>
<td rowspan=2 colspan=2>G</td>
</tr>
<tr></tr>
<tr>
<td rowspan=3 colspan=3>H</td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td colspan=3>I</td>
</tr>
</table>
Try this:
<table id="tbl">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="2" rowspan="2">A</td>
<td rowspan="2">C</td>
</tr>
<tr>
<td rowspan="2">E</td>
</tr>
<tr>
<td>F</td>
<td>G</td>
</tr>
</table>
Script:
var finalResult = '';
var totalTds = $('#tbl TR')[0].length;
var trArray = [];
var trArrayValue = [];
var trIndex = 1;
$('#tbl TR').each(function(){
var currentTr = $(this);
var tdIndex = 1;
trArray[trIndex] = [];
trArrayValue[trIndex] = [];
var tdActuallyTraversed = 0;
var colspanCount = 1;
$('#tbl TR').first().children().each(function(){
if(trIndex > 1 && trArray[trIndex - 1][tdIndex] > 1)
{
trArray[trIndex][tdIndex] = trArray[trIndex - 1][tdIndex] - 1;
trArrayValue[trIndex][tdIndex] = trArrayValue[trIndex - 1][tdIndex];
finalResult = finalResult + trArrayValue[trIndex][tdIndex];
}
else
{
if(colspanCount <= 1)
{
colspanCount = currentTr.children().eq(tdActuallyTraversed).attr('colspan') != undefined ? currentTr.children().eq(tdActuallyTraversed).attr('colspan') : 1;
}
if(colspanCount > 1 && tdIndex > 1)
{
trArray[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed + colspanCount).attr('rowspan') != undefined ?currentTr.children().eq(tdActuallyTraversed + colspanCount).attr('rowspan') : 1;
trArrayValue[trIndex][tdIndex] = trArrayValue[trIndex][tdIndex - 1];
colspanCount--;
}
else
{
trArray[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed).attr('rowspan') != undefined ?currentTr.children().eq(tdActuallyTraversed).attr('rowspan') : 1;
trArrayValue[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed).html();
tdActuallyTraversed++;
}
finalResult = finalResult + trArrayValue[trIndex][tdIndex];
}
tdIndex++;
});
trIndex++;
});
alert(finalResult);
Fiddle
i am not sure about the performance, but it works well.
what I understood with your question is: You want to split the merged cell with same value and then iterate the table simply by row.
I've created a JSFiddle that will split the merged cells with the same value. Then you'll have a table that can be iterated simply by rows to get the desired output that you specified.
See it running here http://jsfiddle.net/9PZQj/3/
Here's the complete code:
<table id="tbl" border = "1">
<tr>
<td>A</td>
<td>B</td>
<td rowspan="2">C</td>
</tr>
<tr>
<td>D</td>
<td rowspan="2">E</td>
</tr>
<tr>
<td>F</td>
<td>G</td>
</tr>
</table>
<br>
<div id="test"> </div>
Here's the jquery that is used to manipulate the table's data.
var tempTable = $('#tbl').clone(true);
var tableBody = $(tempTable).children();
$(tableBody).children().each(function(index , item){
var currentRow = item;
$(currentRow).children().each(function(index1, item1){
if($(item1).attr("rowspan"))
{
// copy the cell
var item2 = $(item1).clone(true);
// Remove rowspan
$(item1).removeAttr("rowspan");
$(item2).removeAttr("rowspan");
// last item's index in next row
var indexOfLastElement = $(currentRow).next().last().index();
if(indexOfLastElement <= index1)
{
$(currentRow).next().append(item2)
}
else
{
// intermediate cell insertion at right position
$(item2).insertBefore($(currentRow).next().children().eq(index1))
}
}
});
console.log(currentRow)
});
$('#test').append(tempTable);
You can use this Gist. It supports all the requirements by W3C, even "rowspan=0" (which seems to be only supported by Firefox).
My table format is
<table class"tabletop">
<tr>
<td>
<table>
<tr>
<td id="mycol1"></td>
<td id="mycol2"></td>
<td id="mycol3"></td>
<td id="mycol4"></td>
</tr>
</table>
</td>
</tr>
<tr>
</tr>
</table>
I have to count columns(having id's) that are not disabled(or their display is not none) and that are disabled.
Suppose columns disabled are 4 and not disabled are 2.
So it must return disabled: 4 and not disabled: 2
td's are disabled by their id.
eg
mycol1.style.display="none";
Working Solution try this
<script type = "text/javascript" language = "javascript">
function getHiddenColumnCount() {
var tbl = document.getElementById("myTbl");
var HiddenColumnCount = 0;
for(var OuterCounter = 0 ; OuterCounter < tbl.rows.length ; OuterCounter++)
{
for(var InnerCounter = 0 ; InnerCounter < tbl.rows[OuterCounter].cells.length;InnerCounter++)
{
if (tbl.rows[OuterCounter].cells[InnerCounter].style.display == "none")
HiddenColumnCount++;
}
}
alert("There are " + HiddenColumnCount + " Hidden Columns in Table");
}
</script>
You can use
$('table td:visible').length
Try this: fiidle
<table border="1" id="myTbl">
<tr>
<td class="mycol1">
1
</td>
<td class="mycol2">
2
</td>
<td class="mycol3">
3
</td>
<td class="mycol4">
4
</td>
</tr>
</table>
<script>
function hideColumn(columnClass) {
var els = document.getElementsByClassName(columnClass);
for (var i = 0; i < els.length; i++) {
els[i].style.display = "none";
}
}
hideColumn('mycol1');
hideColumn('mycol2');
function getHiddenColumnsCount() {
var rows = document.getElementById('myTbl').rows;
var count = 0;
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < rows[i].cells.length; j++) {
if (rows[i].cells[j].style.display == "none")
count++;
}
}
alert(count);
}
getHiddenColumnsCount();
</script>
First of all you should use class for defining column instead of id as id should not be duplicate & to define a column we will have to give similar id to all cells of a column.