user2121189
user2121189

Reputation: 80

jQuery ui selectable table to select/deselect checkboxes

I am trying to build a table grid which represents hourly blocks for each day of the week. What I would like to then do is make each cell in the table selectable, and to check a check box if that cell is selected, or if multiple cells are selected then tick all the check boxes that each cell corresponds to. I have put together a simplified version here: http://jsfiddle.net/yxAjx/4/.

I've really got as far as putting in the selectable code -

$(function() { $( "#selectable" ).selectable({ filter: ".block" }) });

For example if I clicked and dragged across the first 2 cells in the 'Tue' row I would want the corresponding check boxes to be checked.

The table that contains the check boxes I have no control over as this section of html is generated from the software I am using but I have replicated the lay out of it in my example.

My Javascript and jQuery knowledge is limited so would appreciate any pointers on how to achieve this.

Upvotes: 2

Views: 3190

Answers (1)

Dom
Dom

Reputation: 40459

How about doing something like this:

$(function() {
    $( "#selectable" ).selectable({
        filter: ".block",
        selected: function( event, ui ) {
            var row = $(ui.selected).parents('tr').index(),
                col = $(ui.selected).parents('td').index();
            $('#checks').find('tr').eq(row)
                        .children('td').eq(col)
                        .children('input').addClass('checked').prop('checked', true);
            $('#checks input:not(.checked)').prop('checked', false);
        },
        unselected: function( event, ui ) {
            var row = $(ui.unselected).parents('tr').index(),
                col = $(ui.unselected).parents('td').index();
            $('#checks').find('tr').eq(row)
                        .children('td').eq(col)
                        .children('input').removeClass('checked').prop('checked', false);
        }
    });

    $('#checks input').click(function(){
        var row = $(this).parents('tr').index(),
            col = $(this).parents('td').index();
        if($(this).prop('checked')){
             $('#selectable').find('tr').eq(row)
                        .children('td').eq(col)
                        .children('div').addClass('ui-selected');
        }else{
             $('#selectable').find('tr').eq(row)
                        .children('td').eq(col)
                        .children('div').removeClass('ui-selected');
        }
    });
});

DEMO: http://jsfiddle.net/dirtyd77/yxAjx/9/

Upvotes: 3

Related Questions