table and onClick

B

B. P. TBC

Hi all!

I have a html-document with a table. How can I recognise in the onClick
event-handler, that I which cell of a table clicked?

P.
 
S

stannyc

You have to set the onclick event of the TD tags, not the TABLE itself.
You can do this in a loop, for efficiency:

var myTblCells =
document.getElementById("myTable").getElementsByTagName("td");
for (var t=0,curCell; curCell=myTblCells[t]; t++)
curCell.onclick = someFunction;

The above code is IE-specific, of course -- you'll want to generalize
it to support modern browsers. The someFunction code tells you where
you are:

function someFunction()
{
alert("I'm in row " + this.rowIndex + ", cell " + this.cellIndex);
}

Hope this helps,

Stan Scott
New York City
 
T

Thomas 'PointedEars' Lahn

B. P. TBC said:
I have a html-document with a table. How can I recognise in the onClick
event-handler, that I which cell of a table clicked?

Use Event Bubbling.
<URL:http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-bubbling>

<script type="text/javascript">
function handleClick(e)
{
var t;
if (e && ((t = e.target) || (t = e.srcElement)))
{
... t ...
}
}
</script>

<table onclick="handleClick(event);">
...
</table>


PointedEars
 
T

Thomas 'PointedEars' Lahn

You have to set the onclick event of the TD tags, not the TABLE itself.

Not at all.
You can do this in a loop, for efficiency:

var myTblCells =
document.getElementById("myTable").getElementsByTagName("td");
for (var t=0,curCell; curCell=myTblCells[t]; t++)
curCell.onclick = someFunction;

The above code is IE-specific, of course [...]

It is not, and it is unnecessary. The `click' event bubbles by default
in all implementations.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top