Basic javascript that you should already know

The best minds from Teradata, our partners, and customers blog about whatever takes their fancy.
Teradata Employee

I recently ran across some code that was dynamically displaying a list of checkboxes to the user and when the user checked or unchecked the control an asynchronous call was being made in the onclick handler of the checkbox. Now not knowing how many items could be in the list I was wondering if there could be a performance problem if the list grew to a large size seeing as each one of the items in the list generated its own onclick handler. Also I was wondering if there was another way to handle the list. Sure enough there is a very easy way to do the same thing with only one onclick handler.

It seems that the html events will bubble up to the parent control and on the parent control we can handle the onclick event and then inspect the target of the event and if it is one of our checkboxes then we can do something specific for that checkbox. It is actually very straightforward and pretty easy.

Here is the html for the table

<table onclick="list_onclick(event)"> 
<tr><td><input id="0" type="checkbox" name="id" value="table_row_0" customval="12345"/>Table Row 1</td></tr>
<tr><td><input id="1" type="checkbox" name="id" value="table_row_1" customval="54321"/>Table Row 2</td></tr>

Here is our sample list_onclick event handler

function list_onclick(/*Event*/ e) {
var tgt;
if ((e = e || window.event) && (tgt = e.srcElement || && /INPUT/i.test(tgt.nodeName)) {

Now I don't know if this is more performant than putting an onclick handler on each one of the checkboxes but I assume that if the list was very large then it would be better to have only one onclick handler although I have no proof.

This also works for lists as well and not just tables. So remember when you need to have events happen at a granular level you may not need to actually handle the events at that level.

I have attached a full source file for you to play with because sometimes I just hate snippets.