Conditionally Toggle Form Controls Based On Values - Conditionize

Conditionally Toggle Form Controls Based On Values - Conditionize

Conditionize is a jQuery plugin that toggles the visibility of form controls based on the value(s) of a form field (input, select, checkbox, etc).

1. Download and place the JavaScript file conditionize.min.js after jQuery library.

<script src="https://code.jquery.com/jquery-3.3.1.min.js" 
        integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT" 
        crossorigin="anonymous"></script>
<script src="dist/conditionize.min.js"></script>

2. Apply the condition logic to form controls using the data-cond attribute as follows:

<form class="example" action="#">
  <input type="text" name="text-control" placeholder="Type 'jQueryScript'">
  <div data-cond="[name=text-control] == jQueryScript">Text To Show Once You Typed 'jQueryScript'.</div>
  <select name="select-control">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three. Wow, you will see the new control below...</option>
  </select>
  <div data-cond="[name=select-control] == 3">
    <label>
      <input type="checkbox" name="checkbox-control">
      Is checked?
      <span>
        <span data-cond="[name=checkbox-control] != true">Nope</span>
        <span data-cond="[name=checkbox-control]">Yep</span>
      </span>
    </label>
  </div>
  <div data-cond="[name=select-control] == 3 && [name=checkbox-control] == true">
    <a href="https://github.com/nk-o/conditionize" rel="nofollow" target="_blank">GitHub</a>
  </div>
  
</form>

3. Hide the conditional form fields on page load.

[data-cond] {
  display: none;
}

4. Call the function on the form and done.

$(function(){
  $('.example').conditionize();
});

5. Customize the default selector & attribute:

$('.example').conditionize({
  selector: '[data-cond]',
  conditionAttr: 'data-cond'
});

6. Specify how often to check the condition logic.

$('.example').conditionize({
  checkDebounce: 150
});

7. Customize the toggle function.

$('.example').conditionize({
  // function( $item, show ) { $item[ show ? 'show' : 'hide' ](); }
  customToggle: null, 
});

8. Event handlers.

$('.example').conditionize({
  // function() {}
  onInit: null, 
  // function() {}
  onDestroy: null,
  // function( $item, show ) {} 
  onCheck: null, 
});

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

  • Publication date: 28.09.2018
  • Source