Show/hide Elements With Form Controls - jQuery Conditional Fields

File Size: 2.98 KB
Views Total: 2747
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Show/hide Elements With Form Controls - jQuery Conditional Fields

Conditional Fields is a small jQuery plugin that shows/hides form fields (or any HTML elements) based on values in other form controls.

How to use it:

1. Download and load the jquery.conditional-fields.js script after jQuery.

<script src="https://code.jquery.com/jquery-1.12.4.min.js" 
        integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" 
        crossorigin="anonymous">
</script>
<script src="jquery.conditional-fields.js"></script>

2. Initialize the plugin on document ready and we're ready to go.

$(function(){
  $('body').conditionalFields('init');
});

3. Create trigger controls and conditional elements using the following CSS classes and HTML data attributes:

  • .condition-trigger: trigger selector
  • data-condition: specifies which condition to check on
  • data-condition-value: specifies the value of the condition
<label>
  <input type="radio" name="radioExample" class="condition-trigger" value="0" id="option1" checked> radio1
</label>
<label>
  <input type="radio" name="radioExample" class="condition-trigger" value="1" id="option2"> radio2
</label>
<label>
  <input type="radio" name="radioExample" class="condition-trigger" value="2" id="option3"> radio3
</label>
<div data-condition="radioExample" data-condition-value="0">
  <p>First radio content</p>
</div>
<div data-condition="radioExample" data-condition-value="0;1">
  <p>Second radio content</p>
</div>
<div data-condition="radioExample" data-condition-value="2">
  <p>Thrid radio content</p>
</div>

4. The plugin also supports AND and OR logical operation.

<div data-condition="conditions[]" condition-logical-and data-condition-value="1">
  ...
</div>
<div data-condition="conditions[]" condition-logical-or data-condition-value="1">
  ...
</div>

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