user1584575
user1584575

Reputation: 741

Retrieving Incorrect Table Coordinates

I created a checkers board using tables. I want to retrieve the x and y coordinates of a cell. However, the this.parentNode.rowIndex keeps giving me -1. I've spent countless hours looking for the error. Can anyone find it for me?

var board = [[1, 0, 1, 0, 1, 0, 1, 0],
         [0, 1, 0, 1, 0, 1, 0, 1],
         [1, 0, 1, 0, 1, 0, 1, 0],
         [0, 0, 0, 0, 0, 0, 0, 0],
         [0, 0, 0, 0, 0, 0, 0, 0],
         [0, -1, 0, -1, 0, -1, 0, -1],
         [-1, 0, -1, 0, -1, 0, -1, 0],
         [0, -1, 0, -1, 0, -1, 0, -1]];

var gray = -1; //distinguishing players
var red = 1;

function makeBoard() {
//create a table
var tbl = document.createElement("table");
//create a <tr> for each row
for (var i = 0; i < 8; i++) {
    var tr = document.createElement("tr");

    //create a <td> for each column
    for (var j = 0; j < 8; j++) {
        var td = document.createElement("td");
        //setting the attributes of a square
        td.setAttribute("width", "50");
        td.setAttribute("height", "50");
        if ((i % 2 == 0 && j % 2 != 0) || (i % 2 !=0 && j % 2 == 0)) {
            td.style.backgroundColor = "black";
        }
        else if (board[i][j] == red) {
            td.style.backgroundColor = "red";
        }
        else if (board[i][j] == gray) {
            td.style.backgroundColor = "gray";
        }
        td.onclick = function() {
            alert(this.cellIndex + ", " + this.parentNode.rowIndex); //RETRIEVING WRONG COORDINATES
        }
        tr.appendChild(td);
    }
    tbl.appendChild(tr);
}
tbl.setAttribute("border", "10");
return tbl;
}

If you feel that something is missing, please let me know.

Upvotes: 0

Views: 146

Answers (2)

lostsource
lostsource

Reputation: 21840

The missing tbody doesn't really seem to be the problem in this case. Looks like this is related to the way rows and cells are being added.

Instead of using appendChild you should use table.insertRow and row.insertCell methods

So when adding a row, instead of

var tr = document.createElement("tr");

Use

var tr = tbl.insertRow(0);

Same applied for the cells, use

var td = tr.insertCell(j);

Also remove both appendChild calls for tr and td at the end of your blocks

Working fix here http://jsfiddle.net/nBbd2/30/

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55750

Try using

sectionRowIndex instead of just index..

Seems to be working fine in both chrome and Firefox

this.parentNode.sectionRowIndex

Check Fiddle

Upvotes: 1

Related Questions