Select cells on a row

656 Views Asked by At

I want to select cells in a time table by clicking and dragging, while limiting the selection only happens on the row (say row A) where the selection starts - do nothing if the cursor moves out of row A, and once it's back to row A, select the cells between the first cell and current cell (inclusive).

Currently the general selection works (I have created a jsfiddle here), but I cannot limit the selection on the row where the selection starts, I realized the reason is I cannot get the row and column index in the event handlers, but cannot figure out why:

    var isMouseDown = false;
    var row = -1;    // row to start a selection

    $("#our_table td")
        .mousedown(function () {
        isMouseDown = true;

        row = $(this).parent().index();    // doesn't work!!!

        return false; // prevent text selection
    })

I found an example from here where the row/col index can be retrieved in hover event, but when I put the script into mine, even the selection doesn't work :(

I'm new to this JavaScript stuff, any help would be appreciated.

2

There are 2 best solutions below

3
On BEST ANSWER

If I understood the question:

http://jsfiddle.net/ocu36uwk/11/

use var $tr; to store current row

in .mousedown function set current row $tr = $(this).parent();

in .mouseove function check does the rows are equal:

if (isMouseDown && ($tr[0] === $(this).parent()[0]))
0
On

You need to add the element you want the index from.

These functions should return the index of the row and column of the selected element. You first find a collection of elements, and in the index function you specify the element from the collection you want the index from.

var col = $(this).parent().find("td").index($(this));
var row = $(this).parent().parent().find("tr").index($(this).parent());