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" />

You May Also Like

About the Author: rnowik

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.