tags:

views:

20

answers:

1

I have a table that represents a physical 12x8 grid. Each <td> contains the text name (A1-H12) of the grid co-ordinate. I've added the jquery-ui selectable interaction to the table. I want users to be able to select an arbitrary set of grid co-ordinates. As well as selecting <td>s I'd like the user to be able to select entire rows and/or columns by clicking on the row or column <th>. Selection by <th> is causing me some difficulty:

  1. How do I determine which <td>s are in the same column (or row) as the selected <th>?
  2. Which selectable event should I use to move the selection from a th to the correct set of <td>s? stop, selected or selecting?

My jquery (which only allows me to look at the selected objects since I'm very unsure of how to do things):

$(function(){
 $('#selectable').selectable({
  filter:'td,th',
     selected: function(event, ui){
    console.log(event);
    console.log(ui);
       var s=$(this).find('.ui-selected');
    console.log(s); 
      }
 })

});

The table looks like this:

<table id='selectable'>
  <tr>
     <th>&nbsp;</th><!-- empty cell over row labels-->
     <th class='colhead'>1</th>
...
     <th class='colhead'>12</th>
  </tr>
  <tr>
     <th class='rowhead'>A</th>
     <td>A1</td>
...
     <td>A12</td>
  </tr>
...
  <tr>
     <th class='rowhead'>H</th>
     <td>H1</td>
...
     <td>H12</td>
  </tr>
</table>

A: 

After much trial and error, this is what I figured out. The rowhead selection adds the class to the <td> and undoes the selection of the <th>'s. The colhead selection does the same for the columns, but is a bit more complex since you have to get the column index.

I believe these could be more efficient, but I don't know how. Suggestions are welcome.

$(function(){
    $('#selectable').selectable({
        filter:'td,th',
        stop: function(event, ui){
            $('#selectable th.ui-selected.rowhead').siblings('td').addClass('ui-selected').end().removeClass('ui-selected');
            $('#selectable th.ui-selected.colhead').each(function(i){
                col= $(this).parent().children().index($(this)) +1;
                console.log(col)
                $(this).closest('tr').siblings().children('td:nth-child('+col+')').addClass('ui-selected');
                $(this).removeClass('ui-selected');
            });
        }
    })
});
dnagirl