tags:

views:

119

answers:

2

In javascript, how can we detect which row of the table is clicked? At present what i am doing is, i am binding the the method at run time like this.

onload = function() {
    if (!document.getElementsByTagName || !document.createTextNode) return;
    var rows = document.getElementById('my_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (i = 0; i < rows.length; i++) {
        rows[i].onclick = function() {
            alert(this.rowIndex + 1);
        }
    }
}

[ copied from [ http://webdesign.maratz.com/lab/row%5Findex/ ] ]

But i don't like this approach. Is there any alternative? My problem is just to get the index of the row which is clicked.

  • No jQuery please :D.
+2  A: 

You can use event delegation for that. Basically you add one clickhandler to your table. This handler reads out the tagname of the clicked element and moves up the DOM tree until the containing row is found. If a row is found, it acts on it and returns. Something like (not tested yet, but may give you ideas):

    var table = document.getElementById('my_table');
    table.onclick = function(e) {
       e = e || event;
       var eventEl = e.srcElement || e.target, 
           parent = eventEl.parentNode,
           isRow = function(el) {
                     return el.tagName.match(/tr/i));
                   };

       //move up the DOM until tr is reached
       while (parent = parent.parentNode) {
           if (isRow(parent)) {
             //row found, do something with it and return, e.g.
              alert(parent.rowIndex + 1); 
              return true;
           }
       }
       return false;
   };
KooiInc
A: 

This uses sectionRowIndex to get the index in the containing tBody.

function getRowIndex(e){
 e= window.event || e;
 var  sib, who= e.target || e.srcElement;
 while(who && who.nodeName!= 'TR') who= who.parentNode;
 if(who){
  alert(who.sectionRowIndex+1)
  if(e.stopPropagation) e.stopPropagation();
  else e.cancelBubble= true;
  // do something with who...
 }
}

onload= function(){
 document.getElementById('my_table').onclick= getRowIndex;
}
kennebec