Handling Checkboxes Onclick

On this page we show how to use JavaScript to handle individual checkboxes and groups of checkboxes onclick.

The first step is to obtain references to the checkboxes you wish to attach onclick handlers to. If you are going to handle a single checkbox onclick, you typically get a reference using its ID and then assign a function to its onclick property:

// assign function to onclick property of checkbox
document.getElementById('terms').onclick = function() {
    // access properties using this keyword
    if ( this.checked ) {
        // if checked ...
        alert( this.value );
    } else {
        // if not checked ...
    }
};

Notice that inside the function assigned onclick, we access the checked and value properties of the checkbox using the this keyword.[1] We determine whether the checkbox is checked and can take action based on that.

Handling a Group of Checkboxes Onclick

When you are handling a group of related checkboxes onclick, using getElementById may not be the most practical way of obtaining references to them. We use the following form to demonstrate an alternative approach:

Demo: Handling Checkbox Group

Size: Medium $8.00

Toppings:

To obtain references to the checkboxes in the form, we enclose the checkboxes in a container with an ID. We get a reference to that container using its ID, then use getElementsByTagName to get references to the input elements inside it. Next we use a for loop to inspect the type property of each of the input elements in the node list returned by getElementsByTagName. If the type is checkbox, we assign a function to its onclick property:

// get reference to element containing toppings checkboxes
var el = document.getElementById('toppings');

// get reference to input elements in toppings container element
var tops = el.getElementsByTagName('input');

// assign function to onclick property of each checkbox
for (var i=0, len=tops.length; i<len; i++) {
    if ( tops[i].type === 'checkbox' ) {
        tops[i].onclick = function() {
            // put your awesome code here
        }
    }
}

For our example, the function called onclick updates the total field in the form using the value of the checkbox clicked. The complete JavaScript for the form is displayed below.

JavaScript for Checkboxes Onclick Demo

The JavaScript to handle clicks on the checkboxes and update the total is displayed here with explanation below:

// call onload or in script segment below form
function attachCheckboxHandlers() {
    // get reference to element containing toppings checkboxes
    var el = document.getElementById('toppings');

    // get reference to input elements in toppings container element
    var tops = el.getElementsByTagName('input');
    
    // assign updateTotal function to onclick property of each checkbox
    for (var i=0, len=tops.length; i<len; i++) {
        if ( tops[i].type === 'checkbox' ) {
            tops[i].onclick = updateTotal;
        }
    }
}
    
// called onclick of toppings checkboxes
function updateTotal(e) {
    // 'this' is reference to checkbox clicked on
    var form = this.form;
    
    // get current value in total text box, using parseFloat since it is a string
    var val = parseFloat( form.elements['total'].value );
    
    // if check box is checked, add its value to val, otherwise subtract it
    if ( this.checked ) {
        val += parseFloat(this.value);
    } else {
        val -= parseFloat(this.value);
    }
    
    // format val with correct number of decimal places
    // and use it to update value of total text box
    form.elements['total'].value = formatDecimal(val);
}
    
// format val to n number of decimal places
// modified version of Danny Goodman's (JS Bible)
function formatDecimal(val, n) {
    n = n || 2;
    var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
    while (str.length <= n) {
        str = "0" + str;
    }
    var pt = str.length - n;
    return str.slice(0,pt) + "." + str.slice(pt);
}

// in script segment below form
attachCheckboxHandlers();

Our example form assigns an updateTotal function to the onclick property of each checkbox. As explained in Assigning Functions to Event Handler Properties, a function assigned to an event handler property of an object has access to that object inside the function via the this keyword. In the updateTotal function, a reference to the form containing the checkboxes is obtained through the this keyword, as is the value of the checkbox clicked.

Since the values of form elements are always strings, the parseFloat function is used to convert the current value of the total text box to a floating point number. Then the checkbox's checked property is examined. If the checkbox is checked, its value is added to the current value in the total text box. If not, the value is subtracted from the total. A formatDecimal function is used on the resulting value before placing it in the total text box.

Another example combines the above with radio buttons for a more complete pizza order form.

Example Form Markup

Markup for the example form above is shown here:

<form action="#" method="post" class="demoForm" id="demoForm">
    <fieldset>
        <legend>Demo: Handling Checkbox Group</legend>
        
    <p>Size: Medium $8.00</p>
    
    <div id="toppings">Toppings: 
        <label><input type="checkbox" name="mushrooms" value=".40" /> mushrooms</label>
        <label><input type="checkbox" name="onions" value=".30" /> onions</label>
        <label><input type="checkbox" name="black_olives" value=".40" /> black olives</label>
        <label><input type="checkbox" name="sausage" value=".50" /> sausage</label>
        <label><input type="checkbox" name="pepperoni" value=".50" /> pepperoni</label>
    </div>
    
    <p>
        <label>Total: $ <input type="text" name="total" class="num" size="6" value="8.00" readonly="readonly" /></label>
    </p>
    </fieldset>
    
</form>

  1. We could access other properties of the checkbox the same way, as explained further in the Event Handler Properties Example. Other methods of Attaching Event Handlers could also be used. ^