0

I am kind of new to javascript and trying to accomplish a simple (yet complicated for me) task. I am trying to exclude first row and first column from a table and got stuck in excluding first cell in every row from this table (HTMLTableRowElement). Following is my sample code.

function clickSchedule(){
    var table
    var grow   // group row 
    table= document.getElementById("myTable");
    grow = table.rows;
    for(var i= 1; i<= grow.length ; i++ ){
         var cellIndex = this.cells; 
          for( var j =1 ; j<= cellIndex.length ; j++ ){
               this.onclick = function () {
               alert("test");
               }
         }
    }

The first "for loop" will grab all rows from the table excluding row[0] that is why you can see var i = 1. Next, I am storing cells from all rows to a variable and trying to exclude cell[0] using second "for loop" in order to perform an onclick event to the selected table area.

Also, is it possible to get the index value of the selected cell from this table?

I would really appreciated your help

Faraz Amjad

Faraz_pk
  • 53
  • 5

1 Answers1

0
  1. Your logical part is right and wrong.

    • Start iteration from index 1 is right.

    • i <= grow.length means when it's true, go on iteration. But when i == grow.length, grow[i] should be undefined, because grow.length-1 is the last index. So the right condition expression should be i < grow.length.

  2. You didn't do event binding right in iterations.

    Try this one:

(function(){
  var table = document.querySelector('table')
  var rows = table.rows
  var cells

  for(var i = 1; i < rows.length; i++ ) {
    cells = rows[i].cells
    for(var j = 1; j < cells.length; j++ ) {
      cells[j].onclick = function() {
        alert(this.innerHTML);
      }
    }
  }
})()
<table>
  <tr>
    <td>a1</td><td>a2</td><td>a3</td><td>a4</td>
  </tr>
  <tr>
    <td>b1</td><td>b2</td><td>b3</td><td>b4</td>
  </tr>
  <tr>
    <td>c1</td><td>c2</td><td>c3</td><td>c4</td>
  </tr>
  <tr>
    <td>d1</td><td>d2</td><td>d3</td><td>d4</td>
  </tr>
</table>
Leo
  • 11,955
  • 4
  • 37
  • 58
  • Thanks a million Leo, this works perfectly. Just one more thing how can we get the value of j meaning that onclick value of iteration? Thanks buddy!! – Faraz_pk Apr 28 '15 at 15:58
  • @Faraz_pk are you saying you want to `alert(j)` when cell clicked? – Leo Apr 28 '15 at 16:03
  • alert(j) returns undefined. However, I found the answer it is alert(this.cellIndex) // because alert(this) returns HTMLTableCellElement and cellIndex is its property – Faraz_pk Apr 28 '15 at 16:10