0

I have a html table with 3 columns and 7rows. When I click on a cell its bg is changed to red. I want to make sure that only one cell from each row is selected. So if I am clicking on a cell from row1, which has already a cell selected, I want the prev cell to be deselected and the new cell selected. I want to know how can I figure out that cells are of same row.

3 Answers3

0

If you are using jQuery, in your click handler, do this:

function() {
  $(this).closest('tr').find('td').css('backgroundColor', '');
  $(this).css('backgroundColor', 'red');
}
Holy Joe
  • 116
  • 7
0

You can iterate through the rows, and iterate through the cell in an embedded for loop. The solution provided by John Hartsock on this stackoverflow page should allow you to qualify each cell by row and column.

How do I iterate through table rows and cells in javascript?

Community
  • 1
  • 1
0

Given a table cell, its parentNode will be the containing row, and table rows have a cells property that contains a collection of all the cells. So you can loop through that collection.

function selectCell(cell) {
    var siblings = cell.parentNode.cells;
    for (var i = 0; i < siblings.length; i++) {
        if (i != cell.cellIndex) {
            siblings[i].style.backgroundColor = normalBGColor;
        }
    }
    cell.style.backgroundColor = highlightBGColor;
}
Barmar
  • 596,455
  • 48
  • 393
  • 495