Function: checkboxLimiter [JavaScript]


The checkboxLimiter function will disable all checkboxes, which share common value for the name attribute after the user has checked a pre-set number of them.

The limit number is set in the function source to avoid inconsistency if adding the onChange function call inline of the page source. This does not matter if you are using event listeners, which you should be!

Source Code

/* Checkbox Limiter
* Author: Alexandar Tzanov
* Revised: 2015-08-20
* Version: 01.00.00
* Description: The function will limit enabled checkbox fields based on a
*   common "name" attribute, and a preset "allowed" checkbox count.
* Input: object keyword 'this', numAllowedChecked (set in function)
*/

// Pass the checkbox name to the function
function checkboxLimiter(checkboxField) {
  var checkboxField = checkboxField || null;

  if (checkboxField) {
    var checkboxNameValue = checkboxField.name;
    var numAllowedChecked = 2;  // Number of allowed checked checkbox.
    var checkboxesChecked = [];
    var checkboxes = document.getElementsByName(checkboxNameValue); // Get list of matching checkboxes elements.

    // Check for checked checkboxes.
    for (var i = 0; i < checkboxes.length; i++) {
      if (checkboxes[i].checked) {
        // Add to list of checked checkboxes.
        checkboxesChecked.push(checkboxes[i]);
      }
    }

    // Test and control enabled checkboxes.
    if (checkboxesChecked.length == numAllowedChecked) {
      // Disable all un-checked checkboxes.
      for (var i = 0; i < checkboxes.length; i++) {
        if (!checkboxes[i].checked) {
          checkboxes[i].disabled = true;
        }
      }
    } else {
      // Enable all disabled checkboxes.
      for (var i = 0; i < checkboxes.length; i++) {
        if (checkboxes[i].disabled) {
          checkboxes[i].disabled = false;
        }
      }
    }
  }
}

Usage

checkboxLimiter(this);

Parameters

NameDefinitionDefault Value
thisThe calling node object. Must have a “name” property.required

Return

There is no return value.

Examples

Inline of page source code.

<label for="checkBox1">1. Checkbox<input type="checkbox" value="checkBox1" id="checkBox1" name="checkboxSet[]" onclick="checkboxLimiter(this)"></label>

Adding it via an event listener.

document.getElementById("checkBox1").addEventListener("click", function(){checkboxLimiter(this);}, false);

Revision History

DateVersionChanges
2015-08-2001.00.00Initial release.


Discover more from Titan Fusion

Subscribe to get the latest posts sent to your email.


Discover more from Titan Fusion

Subscribe now to keep reading and get access to the full archive.

Continue reading