views:

31

answers:

2

We have a simple table with say (nxm matrix) and the user will randomly select a set of entries based on the following conditions.

Our layout is like this (just pseudo code)

<table>
   <thead>
      <tr>
          c:forEach 1...31
          <th></th>
      </tr>
   </thead>

   <tbody>
       <tr> // could be 30 | 40 | 50 rows
           <td>1...31</td> // Just mentioned that there would be as much cells as looped on the c:forEach above
       </tr>
   </tbody>
</table>

a] On cell selection we would like to flip the cell color (i.e. ) between blue, yellow. The color should toggle on a particular cell selection. b] If the user selects the header panel (e.g. anything between 1...31) the corresponding column (i.e. all cells in that column) should toggle between blue, yellow

We were thinking using invisible checkboxes to do this, but we haven't got the javascript (we use jquery) logic to select and unselect this correctly. need pointers here, to implement this capability.

+1  A: 

jQuery is a great library. You can use the nth-child() selector to retrieve things like columns. Something maybe like this:

$('table thead th').click(function () {
  // Quick access to the index of this column.
  // Add an extra 1 to this because later nth-child is 1-indexed.
  var idx = $(this).prevAll('th').size() + 1;

  $('table tbody tr td:nth-child(' + idx + ')').css({
    'background-color': 'green'
  });
})

As a general approach. I don't know what kind of logic processing you want in there and where your colors fit, but this should help.

g.d.d.c
+1  A: 

You could do something like this, after adding appropriate css classes:

Deal with cells:

$('table#yourtable').find('tbody td').click( function(){
    $(this).toggleClass('yellow');
    // flip yellow on or off
    // you can figure out how to deal with other states
});

Deal with columns:

$('table#yourtable').find('thead th').click( function(){
    var col = $(this).prevAll().length; // had siblings, should be prevall
    $('table#yourtable').find('tbody tr').each( function(){
        $(this)
            .find('td:eq('+col+')')  // nth column
            .removeClass('yellow blue neutral') // reset colors
            .addClass('green'); // add a color
    });
});

Not tested, and this can undoubtedly be optimized further, but it should give you some ideas.

Ken Redler
This doesn't return the right value: `var col = $(this).siblings().length + 1;`. Siblings looks to both sides of an element. If I click on column 2 with 10 columns this returns 10, not 2.
g.d.d.c
Yup, you got me. Updated it to prevall.
Ken Redler
Not to be nit-picky, but you're also missing concatenation on `.find('td:eq(col)')`. Not sure if that was in there before the edits or if I missed it the first time.
g.d.d.c
@gddc - Hey, it's not nitpicky if it stops it from working. This is my signal that it's time to close the laptop.
Ken Redler