Posts from Thursday, May 29th, 2008

Need Help With Table Row Events

Published 15 years, 9 months past

Here’s a late-week call for assistance in the JavaScript realm, specifically in making IE do what I need and can make happen in other browsers.  I’d call this a LazyWeb request except I’ve been trying to figure out how to do it all [censored] afternoon, and it doesn’t [censored] work no matter how many [censored] semi-related examples I find online that work just [censored] fine, but still don’t [censored] help me [censored] fix this [censored] problem.  [doubly censored]!

I have a table.  (Yes, for data.)  In the table are rows, of course, and each row has a number of cells.  I want to walk through the rows and dynamically add an ‘onclick’ event to every row.  The actual event is slightly different for each row, but in every case, it’s supposed to call a function and pass some parameters (which are the things that change).  Here’s how I’m doing it:

var event = '5'; // in the real code this is passed into the surrounding function
var mapStates = getElementsByClassName('map','tr');
for (x = 0; x < mapStates.length; x++) {
	var el = mapStates[x];
	var id = el.getAttribute('id');
	var val = "goto('" + id + "','" + event + "');";
	el.setAttribute('onclick',val);
}

Okay, so that works fine in Gecko.  It doesn't work at all in IE.  I changed el.setAttribute('onclick',val); to el.onclick = val; per some advice I found online and that completely failed in everything.  Firebug told me "el.onclick is not a function".  Explorer just silently did nothing, like always.

So how am I supposed to make this work in IE, let alone in IE and Gecko-based and WebKit-based and all other modern browsers?

Oh, and do not tell me that framework X or library Q does this so easily, because I'm trying to learn here, not have someone else's code hand-wave the problem away.  Pointing me directly to the actual code block inside a framework or library that makes this sort of thing possible:  that's totally fine.  I may not understand it, but at least there will be JS for me to study and ask questions about.  Ditto for pointing me to online examples of doing the exact same thing, which I tried to find in Google but could not: much appreciated.

Help, please?

Update: many, many commenters helped me see what I was missing and therefore doing wrong---thank you all!  For those wondering what I was wondering, check out the comments.  There are a lot of good examples and quick explanations there.


Browse the Archive