Thursday, August 20, 2015

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 fill 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

Name Definition Default Value
this The calling node object. Must have a “name” property. required

Return

There is no return.

Examples

Inline of page source.

<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

Date Version Changes
2015-08-20 01.00.00 Initial release.

No comments:

Post a Comment