jqueryjquery-uiselectable

How to select only one column in a table using jQuery UI selectable?


What I am trying to do is allow the user to select rows from a single column at a time using jQuery UI selectable.

What I need to do though is restrict the drag/highlight effect from spanning more than one column. E.g. which ever column the user start the drag event in they cant highlight out side that column.

Table code

<table id="selectable">
  <tr>
    <td data-col="0">
    <td data-col="1">
    <td data-col="2">
  </tr>
  <tr>
    <td data-col="0">
    <td data-col="1">
    <td data-col="2">
  </tr>
  <tr>
    <td data-col="0">
    <td data-col="1">
    <td data-col="2">
  </tr>
  ...etc
</table>

jQuery:

var currentCol;

$("#selectable").selectable({
    filter:'td',
    selecting: function(event, ui){
        console.log($(ui.selected));
    }
});

But I cant access the value of data-col, it's always null.


Solution

  • Thanks to Daniel for pointing me in the right direction.

    In order to lock the drag down top a single column, this is what I did.

        var currentCol;
    
        $("#selectable").selectable({
            filter: "td",
            start: function(event, ui) {
                $("td").removeClass("ui-selected");
            },
            stop: function(event, ui) {
    
                //Reset selector. 
                currentCol = undefined;
            },
            selecting: function(event, ui) {
    
                if (currentCol === undefined) {
                    currentCol = $(ui.selecting).attr('data-col');
                }
    
                var nthChild = parseInt(currentCol) + 1; //Add one as nthChild is not zero index
    
                for (var i = 1; i <= 9; i++) {
    
                    if (i != nthChild) {
                        $("td.ui-selecting:nth-child(" + i + ")").each(function() {
                            $(this).removeClass("ui-selecting");
                        });
                    }
                }
                ;
            }
        });