Question

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.

Was it helpful?

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");
                    });
                }
            }
            ;
        }
    });

OTHER TIPS

If all you care about is the column index, this should work to get it:

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

Also $(ui.selecting).attr('data-col') should work if you still want to use that method. In your example, you're using ui.selected where you should be using ui.selecting.

jsFiddle

Remember that you can use the JQuery selector td:nth-child($column_index) (the index start from 1)

$("#selectable").selectable({
    filter: "td:nth-child(1)",
    selecting: function (e, ui) {
         $(ui.selecting).css({'border':'1px solid black'})
    },
    unselecting: function (e, ui) {
         $(ui.unselecting).css({ 'border': '' })
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top