HTML checkbox onclick called in Javascript


I am having a bit of trouble trying to figure out how to get a certain part of my code to work.

<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" onclick="selectAll(document.wizard_form, this);">
<label for="check_all_1" onclick="toggleCheckbox('check_all_1'); return false;">Select All</label>

This is my HTML which works as it should (clicking the text will click the box). The javascript for it is pretty simple:

function toggleCheckbox(id) {
    document.getElementById(id).checked = !document.getElementById(id).checked;

However I want the onclick to happen for the input when the label is what makes the checkbox to be clicked. At this current time the onClick js does not go. What is one suggestion on how to do this? I tried to add the onclick of the input to the onclick of the label but that doesn't work.

Any suggestions/solutions would be wonderful.

7/7/2010 6:25:11 PM

Accepted Answer

How about putting the checkbox into the label, making the label automatically "click sensitive" for the check box, and giving the checkbox a onchange event?

<label ..... ><input type="checkbox" onchange="toggleCheckbox(this)" .....> 

function toggleCheckbox(element)
   element.checked = !element.checked;

This will additionally catch users using a keyboard to toggle the check box, something onclick would not.

7/7/2010 6:28:42 PM

Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll() when you click on a label, right? Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label

<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
  <input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
  Select All

jQuery has a function that can do this:

  1. include the following script in your head:

    <script type="text/javascript" src=""></script>

    (or just download the jQuery.js file online and include it locally)

  2. use this script to toggle the check box when the input is clicked:

    var toggle = false;
    $("#INPUTNAMEHERE").click(function() {
            toggle = !toggle;

That should do what you want if I understood what you were trying to do.


You can also extract the event code from the HTML, like this :

<input type="checkbox" id="check_all_1" name="check_all_1" title="Select All" />
<label for="check_all_1">Select All</label>

function selectAll(frmElement, chkElement) {
    // ...
document.getElementById("check_all_1").onclick = function() {
    selectAll(document.wizard_form, this);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]