state boxes grid

http://stackoverflow.com/q/11979586/922168

by nickaknudson

HTML

<table border=1px>
<tr>
    <td><div class="checkbox">1</div></td>
   <td><div class="checkbox">2</div></td>
    <td><div class="checkbox">3</div></td>
   <td><div class="checkbox">4</div></td>
    <td><div class="checkbox">5</div></td>
   <td><div class="checkbox">6</div></td>
    </tr> 
<tr>       
    <td><div class="checkbox">7</div></td>
   <td><div class="checkbox">8</div></td>
    <td><div class="checkbox">9</div></td>
   <td><div class="checkbox">10</div></td>
    <td><div class="checkbox">11</div></td>
   <td><div class="checkbox">12</div></td>
    </tr>
<tr>      
    <td><div class="checkbox">13</div></td>
   <td><div class="checkbox">14</div></td>
    <td><div class="checkbox">15</div></td>
   <td><div class="checkbox">16</div></td>
    <td><div class="checkbox">17</div></td>
   <td><div class="checkbox">18</div></td>
</tr>
</table>

CSS

.checkbox {
    width: 30px;
    height: 30px;
    border: 1px solid #000;
    text-align: center;
    font-size: 14px;
    line-height: 30px;
    cursor: pointer;
    margin: 5px;
    border-radius: 5px;
    border-width: 3px;
    font-weight: 700;
}
.checkbox.checked {
    border-color: green;
}
.checkbox.unchecked {
    border-color: red;
}
.checkbox.none {
    border-color: blue;
    background-color: #eee;
    color: #777;
}

JavaScript

var State = {
    CHECKED: 'checked',
    UNCHECKED: 'unchecked',
    NONE: 'none'
};

states = [];
table = new Array();

$.each(State, function(k, state) {
    states.push(state);
});

$rows = $('table').children().children();
$rows.each(function(row_index, elm) {
    table[row_index] = new Array();
    $row = $(elm);
    $cols = $row.children();
    $cols.each(function(col_index, elm) {
        table[row_index][col_index] = $col = $(elm).children();
        console.log($col, table[row_index][col_index]);
    });
});

function getState(el$) {
    return el$.data('state') || State.UNCHECKED;
}

function setState(el$, state) {
    var oldState = getState(el$);
    el$.data('state', state).removeClass(oldState).addClass(state);
}

function onDrop(event, ui) {
    var droppable$ = $(this),
        newState = getState(ui.draggable);
    console.log(droppable$);
    setState(droppable$, newState);
}

function onClick() {
    var checkbox$ = $(this),
        state = getState(checkbox$);
    stateIndex = states.indexOf(state) + 1;
    if (stateIndex > states.length - 1) {
        stateIndex = 0;
    }
    currentState = states[stateIndex];
    setState(checkbox$, currentState);
}

function onDragStart() {
    $(this).off('click', onClick);
}

function onDragStop() {
    $(this).on('click', onClick);
}

$('.checkbox').on('click', onClick).draggable({
    revert: true,
    revertDuration: 200,
    delay: 100,
    start: onDragStart,
    stop: onDragStop
}).droppable({
    accept: '.checkbox',
    drop: onDrop,
    over: onDrop
});