This is a migrated thread and some comments may be shown as answers.

$(cell).index() INTERMITTENTLY returns the wrong cell index

2 Answers 267 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Tim R
Top achievements
Rank 1
Tim R asked on 13 Mar 2013, 10:35 PM
EDIT: It's happening because the TD sometimes contains a DIV and the DIV, not the TD, becomes the target of the click event.

I posted this by accident in Window sub-forum.

It may be my error, or it could be a problem with the grid or jQuery.  My code is shown below.  I'm clicking on the same column, choosing a different row at random, and every so often, the wrong column-index is returned. I cannot figure out why it works most of the time, but not always.  I'm clicking on a column whose index is 7. Sometimes zero is returned.

Also tried the following; cellindex and index() are not always in agreement.

function popup(e) {   
          cell = e.target;
            var ix = $(cell).index();
           var ix2 = $(cell)[0].cellIndex;
           assert((ix == ix2), "index() and cellindex returning different values!");
}
 

function addCellClickEventListener() {
    var grid = $('#grid').data('kendoGrid');
    $(grid.tbody).on('click', "> tr:not(.k-grouping-row, .k-detail-row, .k-group-footer) ", function (e) {
        popup(e);
    });
}
  
  
function popup(e) {   
    var cell = e.target;
    var ix = $(cell).index();
    assert((ix != 0), "index must be greater than zero");
}
  
  
function assert(val, msg) {
    if (!val) {
        alert(msg);
        return false;
    }
    return true;
}

2 Answers, 1 is accepted

Sort by
0
Atanas Korchev
Telerik team
answered on 14 Mar 2013, 08:17 AM
Hello Tim,

 This is expected and is how DOM events work. You have attached the click event handler to the <TR> element. By default DOM events bubble which means that clicking **any** child element within this TR will trigger the click event. So if your cell contains a div the div will be e.target. Here is a quote from jQuery's documetnation:

The target property can be the element that registered for the event or a descendant of it.

I recommend attaching the event handler to the TD elements instead and using "this" to always get the table cell:

$(grid.tbody).on('click', "> tr:not(.k-grouping-row, .k-detail-row, .k-group-footer) > td ", function (e) {
        popup(this); // this is the table cell
});

You also need to modify your popup function:
function popup(cell) {   
    var ix = $(cell).index();
    assert((ix != 0), "index must be greater than zero");
}


Regards,
Atanas Korchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Tim R
Top achievements
Rank 1
answered on 14 Mar 2013, 11:48 AM
Thank you, Atanas, for the clear explanation.


Tags
Grid
Asked by
Tim R
Top achievements
Rank 1
Answers by
Atanas Korchev
Telerik team
Tim R
Top achievements
Rank 1
Share this question
or