jQuery count of specific class an element contains - javascript

I have a table and each row in the table has one or more classes depending on the region.
Here is what my table looks like:
<table>
<thead>
<th>Title</th>
<th>Name</th>
</thead>
<tbody>
<tr class="emea apac">
<td>Testing</td>
<td>Bob</td>
</tr>
<tr class="americas">
<td>Testing2</td>
<td>Jim</td>
</tr>
<tr class="emea">
<td>Testing 3</td>
<td>Kyle</td>
</tr>
<tr class="emea americas">
<td>Testing 3</td>
<td>Kyle</td>
</tr>
<tr class="emea apac americas">
<td>Testing 3</td>
<td>Kyle</td>
</tr>
<tr class="apac">
<td>Testing 3</td>
<td>Kyle</td>
</tr>
</tbody>
I am trying to now count specifically how many rows there are where the class is equal to my condition.
For example:
How many rows have ONLY .APAC = 1
How many rows have all 3 of the possible classes? = 1
I started this jsFiddle but couldn't really think of how to approach it from this point: http://jsfiddle.net/carlhussey/gkywznnj/4/

Working from your fiddle (updated)...
$(document).ready(function () {
var apac = 0,
emea = 0,
americas = 0,
combo = 0,
all = 0;
$('table tbody tr').each(function (i, elem) {
var classes = elem.className.split(' '),
hasApac = classes.indexOf('apac') > -1,
hasEmea = classes.indexOf('emea') > -1,
hasAmericas = classes.indexOf('americas') > -1;
apac += (hasApac && !hasEmea && !hasAmericas) ? 1 : 0;
emea += (hasEmea && !hasApac && !hasAmericas) ? 1 : 0;
americas += (hasAmericas && !hasApac && !hasEmea) ? 1 : 0;
if (((hasApac && hasEmea) || (hasApac && hasAmericas) || (hasEmea && hasAmericas)) && classes.length === 2) {
combo += 1;
}
if (hasApac && hasEmea && hasAmericas) {
all += 1;
}
});
$('span[name="apac"]').text(apac);
$('span[name="emea"]').text(emea);
$('span[name="americas"]').text(americas);
$('span[name="combo"]').text(combo);
$('span[name="all"]').text(all);
});
UPDATE
I'm pretty sure jQuery's hasClass method works with IE8, so you could change the .each callback to:
function (i, elem) {
var row = $(elem),
hasApac = row.hasClass('apac'),
hasEmea = row.hasClass('emea'),
hasAmericas = row.hasClass('americas');
apac += (hasApac && !hasEmea && !hasAmericas) ? 1 : 0;
emea += (hasEmea && !hasApac && !hasAmericas) ? 1 : 0;
americas += (hasAmericas && !hasApac && !hasEmea) ? 1 : 0;
if (((hasApac && hasEmea) || (hasApac && hasAmericas) || (hasEmea && hasAmericas)) && elem.className.split(' ').length === 2) {
combo += 1;
}
if (hasApac && hasEmea && hasAmericas) {
all += 1;
}
}
Updated fiddle: http://jsfiddle.net/gkywznnj/6/

var rows = $('tr'),
class = 'americas',
counter = 0;
rows.each(function () {
//If current element have .americas increment counter
if($(this).hasClass(class)) {
counter +=1
}
});
console.log(counter);

http://jsfiddle.net/gkywznnj/8/
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
function countOnlyClass(classFindA)
{
var $trA=$('table tbody tr');
var count=0;
if(classFindA.length>0){
$trA.each(function(){
var c=0;
var m=0;
var $tr=$(this);
var classA = $tr.attr('class').split(' ');
$.each(classA,function(i,cl){
if(classFindA.indexOf(cl)>-1) c++; else m++;
})
if(c>0 && c==classFindA.length && m==0) count++;
})
}
return count;
}
function comboOnlyClass(comboCount)
{
var $trA=$('table tbody tr');
var count=0;
$trA.each(function(){
var countClass = {};
var $tr=$(this);
var classA = $tr.attr('class').split(' ');
$.each(classA,function(i,cl){
if(!cl in countClass )
countClass.cl=1;
})
if(Object.size(classA )==comboCount) count++;
})
return count;
}
var a=countOnlyClass(['apac'])
$('#apac').html(a);
var a=countOnlyClass(['emea'])
$('#emea').html(a);
var a=countOnlyClass(['americas'])
$('#americas').html(a);
var a=countOnlyClass(['apac','emea','americas'])
$('#all').html(a);
var a=comboOnlyClass(2);
$('#combo').html(a);
//var a=comboOnlyClass(1); onlu one class

Related

Sorting Number in Table

I had try to create a table that able to sort the data ascending nor descending by clicking on the table header.
However the data number is not sorting correctly based on 1,3,9,10 instead of 1,10,11,12. Is there any way to sort the number?
function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {
sortTable(table, i, (dir = 1 - dir))
});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
window.onload = function () {makeAllSortable();};
<table class="table table-striped table-bordered table-hover" id="Tabla">
<thead>
<tr style="cursor:pointer">
<th>Fruit<span class="glyphicon pull-right" aria-hidden="true"></span></th>
<th>Number<span class="glyphicon pull-right" aria-hidden="true"></span></th>
</tr>
</thead>
<tr>
<td>Apple</td>
<td>11757.915</td>
</tr>
<tr>
<td>Orange</td>
<td>36407.996</td>
</tr>
<tr>
<td>Watermelon</td>
<td>9115.118</td>
</tr>
</table>
You must add the options to sort numerically to the localCompare call
// --8<-------
.localeCompare(b.cells[col].textContent.trim(), undefined, {numeric: true})
// ------->8--
function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function(a, b) { // sort rows
return reverse // `-1 *` if want opposite order
*
(a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim(), undefined, {numeric: true})
);
});
for (i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
function makeSortable(table) {
var th = table.tHead,
i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0)(function(i) {
var dir = 1;
th[i].addEventListener('click', function() {
sortTable(table, i, (dir = 1 - dir))
});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'),
i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
window.onload = function() {
makeAllSortable();
};
<table class="table table-striped table-bordered table-hover" id="Tabla">
<thead>
<tr style="cursor:pointer">
<th>Fruit<span class="glyphicon pull-right" aria-hidden="true"></span></th>
<th>Number<span class="glyphicon pull-right" aria-hidden="true" data-sort="numerically"></span></th>
</tr>
</thead>
<tr>
<td>Apple</td>
<td>11757.915</td>
</tr>
<tr>
<td>Orange</td>
<td>36407.996</td>
</tr>
<tr>
<td>Watermelon</td>
<td>9115.118</td>
</tr>
</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

Javascript 'onclick' not working in Google Chrome

I am using datatables to dynamically create a table and populate it with data. So far so good. Then I try to use onclick() to make certain td elements clickable so they redirect me to another page.
The problem is: clicking on the td's does absolutely nothing in Chrome. It works fine in IE though.
Here's the html code.
<body id="dt_example">
<form>
<input type="hidden" name="currency_numberOfRows" id="currency_numberOfRows" value="<%=currency_numberOfRows %>"></input>
<input type="hidden" name="currency_numberOfColumns" id="currency_numberOfColumns" value="<%=currency_numberOfColumns %>"></input>
<div id="demo">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="currency_example" tableType="currency_clickableTDs">
<thead><tr>
<th class="heading"></th>
<th class="heading"><%=header_data%></th>
<th>% of Total</th>
<th>Total</th>
</tr></thead>
<tbody>
<tr class="odd">
<th class="heading">*Dynamically Added Heading*</th>
<td valign=middle class="underline">***Clickable Cell***</td>
<td valign=middle>*Dynamically Added Data*</td>
<td valign=middle>*Dynamically Added Data*</td>
</tr>
</tbody>
</table>
</div>
The javascript code is
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var counter=(document.getElementById("currency_numberOfColumns").value)*2+1;
var tempaoColumns = [];
for(i=0;i<=counter;i++){
if(i==0)
{tempaoColumns[i] = null;}
else
{ tempaoColumns[i] = { "sType": "numeric-comma" };}
}
$('table.display').dataTable({
"aoColumns": tempaoColumns,
"sDom": 'T<"clear">lfrtip',
"aaSorting": [[ 1, "desc" ]]
});
} );
</script>
and
function setTDOnclickEvents(val){
var pageFrom = val;
var colHeaders = [];
var rowHeaders = [];
var numberOfColumns = document.getElementById("currency_numberOfColumns").value;
var numberOfRows = document.getElementById("currency_numberOfRows").value;
var table=document.getElementById("currency_example");
for (var h=0; h <= numberOfColumns*2; h++) {
//find every TR in a "clickableTDs" type table
colHeaders[h]= (table.rows[0].cells[h].innerHTML);
//alert(h)
//alert(table.rows[0].cells[h].innerHTML)
}
for (var h=0; h < numberOfRows/2; h++) {
//find every TR in a "clickableTDs" type table
if(h==0)
rowHeaders[h]= (table.rows[h].cells[0].innerHTML);
else if(h==1){
rowHeaders[h]= (table.rows[numberOfRows/2].cells[0].innerHTML);}
Uncaught TypeError: Cannot read property 'cells' of undefined in the above line
else
rowHeaders[h]= (table.rows[h-1].cells[0].innerHTML);
}
var allTRs = new Array();
//go through all elements
if(document.forms[0].tab.value=="Currency"){
for (var h=0; h < document.all.length; h++) {
//find every TR in a "clickableTDs" type table
if (document.all[h].tagName == "TR" &&
document.all[h].parentElement.parentElement.tableType == "currency_clickableTDs") {
allTRs.push(document.all[h]);
}
}
}
else if(document.forms[0].tab.value=="Service"){
for (var h=0; h < document.all.length; h++) {
//find every TR in a "clickableTDs" type table
if (document.all[h].tagName == "TR" &&
document.all[h].parentElement.parentElement.tableType == "service_clickableTDs") {
allTRs.push(document.all[h]);
}
}
}
else if(document.forms[0].tab.value=="Project"){
for (var h=0; h < document.all.length; h++) {
//find every TR in a "clickableTDs" type table
if (document.all[h].tagName == "TR" &&
document.all[h].parentElement.parentElement.tableType == "project_clickableTDs") {
allTRs.push(document.all[h]);
}
}
}
else if(document.forms[0].tab.value=="Location"){
for (var h=0; h < document.all.length; h++) {
//find every TR in a "clickableTDs" type table
if (document.all[h].tagName == "TR" &&
document.all[h].parentElement.parentElement.tableType == "location_clickableTDs") {
allTRs.push(document.all[h]);
}
}
}
for (var i=1; i < allTRs.length; i++) {
for (var j=1; j < allTRs[i].cells.length; j++) {
allTRs[i].cells[j].colHeader = colHeaders[j];
allTRs[i].cells[j].rowHeader = rowHeaders[i];
allTRs[i].cells[j].onclick = function (){
if(this.innerHTML == "0.00" || this.innerHTML == "0"){
alert("No data to represent!!!");
}else{
if((pageFrom == "GrossRevenueLevel") && (this.colHeader != "% of Total")&&(this.colHeader != "TOTAL")){
goMyController(this.colHeader,this.rowHeader);
}
}}
} } }
Could someone please help me? Thanks in advance and sorry for the painfully long code.
P.S. I didn't put the entire html code as it would be too lengthy
I found a solution. I replaced the javascript code with
function setTDOnclickEvents(val){
var pageFrom = val;
var bhal=$("#tab").val();
if(bhal=="Currency"){
var $tables = $("#currency_example tr");
}
else if(bhal=="Service"){
var $tables = $("#service_example tr");
}
else if(bhal=="Project"){
var $tables = $("#project_example tr");
}
else if(bhal=="Location"){
var $tables = $("#location_example tr");
}
$tables.each(function (i, el) {
var $tds = $(this).find('td.underline');
$tds.click(function(){
var hetch = $(this).html();
var hindex = $(this).index();
var colHeada= $tds.closest('table').find('th').eq(hindex).html();
var rowHeada= $tds.closest('tr').find('th').html();
if(hetch == "0.00" || hetch == "0"){
alert("No data available for this selection.");
}else{
if((pageFrom == "GrossRevenueLevel") && (colHeada != "% of Total")&&(colHeada != "TOTAL")){
alert(colHeada);
alert(rowHeada);
}
}
});
});
}
and it's working now.

Iterate over table cells, re-using rowspan values

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).

Finding column index using jQuery when table contains column-spanning cells

Using jQuery, how can I find the column index of an arbitrary table cell in the example table below, such that cells spanning multiple columns have multiple indexes?
HTML
<table>
<tbody>
<tr>
<td>One</td>
<td>Two</td>
<td id="example1">Three</td>
<td>Four</td>
<td>Five</td>
<td>Six</td>
</tr>
<tr>
<td colspan="2">One</td>
<td colspan="2">Two</td>
<td colspan="2" id="example2">Three</td>
</tr>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
<td>Five</td>
<td>Six</td>
</tr>
</tbody>
</table>
jQuery
var cell = $("#example1");
var example1ColIndex = cell.parent("tr").children().index(cell);
// == 2. This is fine.
cell = $("#example2");
var example2ColumnIndex = cell.parent("tr").children().index(cell);
// == 2. It should be 4 (or 5, but I only need the lowest). How can I do this?
Here's a plugin which can calculate the 'noncolspan' index.
$(document).ready(
function()
{
console.log($('#example2').getNonColSpanIndex()); //logs 4
console.log($('#example1').getNonColSpanIndex()); //logs 2
}
);
$.fn.getNonColSpanIndex = function() {
if(! $(this).is('td') && ! $(this).is('th'))
return -1;
var allCells = this.parent('tr').children();
var normalIndex = allCells.index(this);
var nonColSpanIndex = 0;
allCells.each(
function(i, item)
{
if(i == normalIndex)
return false;
var colspan = $(this).attr('colspan');
colspan = colspan ? parseInt(colspan) : 1;
nonColSpanIndex += colspan;
}
);
return nonColSpanIndex;
};
Mine is quite similar to SolutionYogi's, minus the creation of a plugin. It took me a bit longer... but I'm still proud of it so here it is :)
cell = $("#example2");
var example2ColumnIndex2 = 0;
cell.parent("tr").children().each(function () {
if(cell.get(0) != this){
var colIncrementor = $(this).attr("colspan");
colIncrementor = colIncrementor ? colIncrementor : 1;
example2ColumnIndex2 += parseInt(colIncrementor);
}
});
console.log(example2ColumnIndex2);
There is a more concise answer here: Get Index of a td considering the colspan using jquery
In short:
var index = 0;
$("#example2").prevAll("td").each(function() {
index += this.colSpan;
});
console.log(index);
You could do something like this:
var index = 0;
cell.parent('tr').children().each(
function(idx,node) {
if ($(node).attr('colspan')) {
index+=parseInt($(node).attr('colspan'),10);
} else {
index++;
}
return !(node === cell[0]);
}
);
console.log(index);
It'd probably make sense to do it as a plugin or via extend.
Slightly modified version is here: http://jsfiddle.net/Lijo/uGKHB/13/
//INDEX
alert ( GetNonColSpanIndex ('Type'));
function GetNonColSpanIndex(referenceHeaderCellValue) {
var selectedCell = $("th").filter(function (i) {
return ($.trim($(this).html() )) == referenceHeaderCellValue;
});
alert(selectedCell.html());
var allCells = $(selectedCell).parent('tr').children();
var normalIndex = allCells.index($(selectedCell));
var nonColSpanIndex = 0;
allCells.each(
function (i, item) {
if (i == normalIndex)
return false;
var colspan = $(selectedCell).attr('colspan');
colspan = colspan ? parseInt(colspan) : 1;
nonColSpanIndex += colspan;
}
);
return nonColSpanIndex;
};
​

Categories

Resources