Show Related Content if Checkbox Checked

On this page we demonstrate and describe how you can show or hide content related to a checkbox depending upon whether that checkbox is checked or not.

To accomplish this, we get a reference to the checkbox and assign a function to its onclick property. Each time the checkbox is clicked, a function is called which determines whether the checkbox is checked. If so the related content is displayed; otherwise its display property is set to none.

Click the checkbox below to see.

Demo: Show/Hide Related Onclick

Check if you engage in sports or fitness activities on a regular basis.

Check which types

JavaScript for Checkbox Show/Hide Onclick

The JavaScript for the example is displayed here:

// assign function to onclick property of checkbox
document.getElementById('active').onclick = function() {
    // call toggleSub when checkbox clicked
    // toggleSub args: checkbox clicked on (this), id of element to show/hide
    toggleSub(this, 'active_sub');
};

// called onclick of checkbox
function toggleSub(box, id) {
    // get reference to related content to display/hide
    var el = document.getElementById(id);
    
    if ( box.checked ) {
        el.style.display = 'block';
    } else {
        el.style.display = 'none';
    }
}

This approach could be used for multiple checkboxes that have related content. Assign functions to their onclick properties the same way, and pass the ID of their related content as the second argument to the toggleSub function.

Other approaches to attaching event handlers could be used instead, as discussed in our tutorial on JavaScript Event Handling.

Example Form Markup

Markup for the example is displayed here:

<form action="#" method="post" class="demoForm" id="demoForm">
    
    <fieldset>
        <legend>Demo: Show/Hide Related Onclick</legend>
    
    <p><input type="checkbox" name="active" id="active" value="1" /> Check if you engage in sports or fitness activities on a regular basis.</p>
    
    <div id="active_sub">
        <p><span>Check which types</span>
        <label><input type="checkbox" name="sports[]" value="cycling" /> cycling</label>
        <label><input type="checkbox" name="sports[]" value="running" /> running</label>
        <label><input type="checkbox" name="sports[]" value="visit gym" /> visit gym</label>
        <label><input type="checkbox" name="sports[]" value="swimming" /> swimming</label>
        <label><input type="checkbox" name="sports[]" value="team sports" /> team sport(s)</label>
        <label><input type="checkbox" name="sports[]" value="other" /> other</label></p>
    </div>
    
    </fieldset>
    
</form>