SVicente's Blog

Follow me and you'll know what I like to do

Javascript code – attach event to checkboxes

<title>How to dynamically attach a checkbox event click</title>
<script type=”text/javascript”>

// c&p from
function addEvent(obj, type, fn)
if (obj.attachEvent)
obj[‘e’ + type + fn] = fn;
obj[type + fn] = function(){obj[‘e’ + type + fn](window.event);}
obj.attachEvent(‘on’ + type, obj[type + fn]);
obj.addEventListener(type, fn, false);
function removeEvent( obj, type, fn ) {
if( obj.detachEvent ) {
obj.detachEvent( ‘on’+type, obj[type+fn] );
obj[type+fn] = null;
} else
obj.removeEventListener( type, fn, false );

// Function below is based on an example get from

function fCheckBox(e)
var id =;
var checked = document.getElementById(id).checked;
if (checked == true)
// item was checked.  save new site assignment for this user
alert(“Checkbox #id=”+id+” was clicked and checked.”);
// item was unchecked.  remove this site assignment for this user
alert(“Checkbox #id=”+id+” was clicked and unchecked.”);

function addEvents2CheckBox() {
for(var i=0; i<document.form.length; i++) {
addEvent(document.form.elements[i], “click”, fCheckBox);


<body onload=”addEvents2CheckBox()”>

<form name=”form” method=”post” action=””>
<input type=”checkbox” id=”chk1″>Check #1<br>
<input type=”checkbox” id=”chk2″>Check #2<br>
<input type=”checkbox” id=”chk3″>Check #3<br>
<input type=”checkbox” id=”chk4″>Check #4<br>
<input type=”checkbox” id=”chk5″>Check #5<br>


May 30, 2009 - Posted by | Web Development |


  1. It will not works in IE6.

    Comment by martin | January 7, 2010 | Reply

    • Ok, I still have a machine where IE6 is running. I will try to fix it out. Tks.

      Comment by svicente99 | January 7, 2010 | Reply

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: