You really should become familiar with your browsers' debugger.
Opening up the debugger would have shown you that there's a problem with your getVal function.
In it, you use the term:
row.cells(0).innerHTML
- only problem is that the cells object is an array - not a function. I.e at the moment you're passing it a variable of 0 and asking
it to calculate which cell that refers to and return a reference to it. It doesn't work like that - you just need to tell the
javascript engine which
element of the cells array you'd like.
Here's a fully worked example:
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
window.addEventListener('load', mInit, false);
function mInit()
{
var myTable = makeTable(5, 5, 'tblMain');
var i, n, curRow;
n = myTable.rows.length;
for (i=0; i<n; i++)
myTable.rows[i].addEventListener('click', onRowClick, false);
byId('tableHolder').appendChild(myTable);
}
function onRowClick(e)
{
var value1, value2;
value1 = this.cells[0].innerHTML;
value2 = this.cells[1].innerHTML;
byId('output1').value = value1;
byId('output2').value = value2;
}
function makeTable(nCols, nRows, idTxt)
{
var x, y, curRow, curCell, tbl = newEl('table');
tbl.setAttribute('id', idTxt);
for (y=0; y<nRows; y++)
{
curRow = tbl.insertRow();
for (x=0; x<nCols; x++)
{
curCell = curRow.insertCell();
curCell.innerHTML = "Cell: ["+ (nCols-x) +","+ (nRows-y) +"]";
}
}
return tbl;
}
</script>
<style>
</style>
</head>
<body>
<div id='tableHolder'></div>
<input id='output1' />
<br>
<input id='output2' />
</body>
</html>
Note: because the event handlers are attached via code in this manner, we have access to a special variable,
this
It refers to the object that has the event handler attached to it. That's why I can use the this keyword in the click handler - the handler is attached to each row of the table. When run, onRowClick's
this
points to the row that was clicked.
Attaching the event as you have has a number of disadvantages.
(1) You need to use a 'shim' function
i.e
function () {
getval(this);
};
(2) Each time you assign an event like this, it replaces any and all handlers already attached to that element (you need to use addEventListener to attach more than 1 func to an element)
(3) You can't remove a single handler at a time - it's all-or-nuthin'