JavaScript: Dynamically adding an onclick event

The code below shows how to dynamically add an onclick event to a checkbox input element. The most important thing to note is that onclick must be set using a reference to a function (i.e. with no parentheses).

<title>JS Test</title>
<script language="javascript">
function addOnClickEvent()
    var element = document.getElementById("testcheckbox");
    element.onclick = generateMessage;
function generateMessage(message)
    alert("Hello World");
<body onload="addOnClickEvent();">
  <form action="jstest.htm" method="post">
    <input type="checkbox" id="testcheckbox" />
    <input type="submit" name="submit" value="submit" />

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>