I am writing a JavaScript function to highlight the row and column of a clicked cell. This function must take into account cells in previous rows that use "rowspan" to protrude down into the selected row - because this causes the cell indexes to differ from the "apparent" index. I.E. every cell in the second column of a table does not necessarily have cellIndex==1
.
To compensate, I have written the following function that calculates the "offset" for each effected cell.
function OffsetCells($tbody) {
// if already indexed, we don't need to re-do it
if (!$tbody.data('isOffset').value) {
// set offset for all cells to zero
$tbody.find('td').data('offset', { value: 0 });
// it's not already indexed, so get the cells that span multiple rows
// capitalization of 'rowSpan' is important for IE
var $rowSpanners = $tbody.find('td[rowSpan!=1]');
$rowSpanners.each(function() {
var $rowSpanningCell = $(this);
// we need to select all the cells to the 'apparent' right of this cell,
// so we need this cell's apparent position
// multiplying by one is easier than parseInt() to ensure conversion
$rowSpanningCell.data('apparentIndex', { value: this.cellIndex * 1 + $rowSpanningCell.data('offset').value });
// we also need to know what row this cell is in
/*???*/ $rowSpanningCell.data('rowIndex', { value: $rowSpanningCell.parent('tr').get(0).rowIndex });
// down to business:
$tbody.parent('table') // get the whole table
.find('tr') // get all the rows in the table
.slice($rowSpanningCell.data('rowIndex').value + 1, $rowSpanningCell.data('rowIndex').value + this.rowSpan) // narrow selection to the applicable rows
.find('td') // get the cells in the chosen rows
.filter(function(index) { // get the cells to the apparent right of this one.
return index + $(this).data('offset').value >= $rowSpanningCell.data('apparentIndex').value;
}).each(function() {
$(this).data('offset', { value: $(this).data('offset').value + 1 });
});
});
$tbody.data('isOffset', { value: true });
}
}
This code works wonderfully in IE, but fails silently at the /???/ line. I have narrowed it down to the $rowSpanningCell.parent('tr').get(0).rowIndex
part. I have tried everything I can think of, and still cannot get it to return the rowIndex value. When I change the code to alert($rowSpanningCell.parent('tr').get(0).nodeName)
I get the expected <TR>
, so I know I my selection is right. Every other value for every OTHER property for the row seems to return fine - but rowIndex just stops the code cold.