jQuery Plugin For Conditional Logic Form Functionality - toggleFields.js

jQuery Plugin For Conditional Logic Form Functionality - toggleFields.js

toggleFields.js is a jQuery plugin for the conditional logic form functionality that automatically enables and disables form fields based on the previous selection.

1. To get started, just place the jQuery toggleFields.js after jQuery JavaScript library and you're ready to go.

<script src="//code.jquery.com/jquery.min.js"></script>
<script src="src/jquery.toggleFields.js"></script>

2. Create a trigger element on the webpage. You're allowed to set multiple conditions which should be separated with a comma and space.

<i aria-hidden data-toggle-conditions="#demo"></i>

3. Add your own conditional logic to the form fields using the following data attribute.

  • data-toggle-target: Target element to be toggled.
  • data-toggle-next: Required if using multiple conditions. 
  • data-toggle-ref:  Wrapping element of the targets. Matches the ID in the 'data-toggle-conditions' attribute.
  • data-toggle-next: Wrapping element of the target form fields.
  • data-toggle-recursive: Identify a recursive condition; one that relies on another condition.
<form>
  <label for="label_id_1">Select an option</label>
  <select id="label_id_1" data-toggle-target>
    <option>---------</option>
    <option id="demo">Condition 1</option>
  </select>
  <div data-toggle-next data-toggle-ref="demo">
    <label data-toggle-target for="label_id_2">An additional field</label>
    <select id="label_id_2" data-toggle-target>
      <option>---------</option>
      <option>Enabled</option>
    </select>
  </div>
</form>

4. Call the function on the form element. That's it.

$('form').toggleFields();

5. Default data attributes and CSS classes/identifiers.

$('form').toggleFields({
  conditionIdentifier: 'data-toggle-condition',
  conditionsIdentifier: 'data-toggle-conditions',
  disabledClass: 'disabled',
  disabledAttr: 'disabled',
  helpTextIdentifier: 'form-row__instructions',
  nextFormRowsIdentifier: 'data-toggle-next',
  nextRowReferenceIdentifier: 'data-toggle-ref',
  targetIdentifier: 'data-toggle-target',
  toggleClass: 'js-toggleFields--on',
});

6. Default callback functions.

$('form').toggleFields({
  initCallback: function initCallback() {},
  toggleOnCallback: function toggleOnCallback() {},
  toggleOffCallback: function toggleOffCallback() {},
  destroyCallback: function destroyCallback() {}
});

This awesome jQuery plugin is developed by nomensa. For more Advanced Usages, please check the demo page or visit the official website.

  • Publication date: 03.12.2017
  • Source