SVicente's Blog

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

Javascript code – attach event to checkboxes

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

// c&p from http://ejohn.org/projects/flexible-javascript-events/
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]);
}
else
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
// http://bytes.com/topic/javascript/answers/725305-please-help-javascript-dynamic-checkboxes-events-question

function fCheckBox(e)
{
var id = e.target.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.”);
}
else
{
// 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);
}
}

</script>
</head>

<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>
</form>
</body>
</html>

May 30, 2009 - Posted by | Web Development |

2 Comments »

  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:

WordPress.com Logo

You are commenting using your WordPress.com 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: