Show & Hide Form Fields Conditionally - jQuery dependent.fields.js

File Size: 3.84 KB
Views Total: 11383
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Show & Hide Form Fields Conditionally - jQuery dependent.fields.js

Just another jQuery plugin for handling conditional forms that have the ability to show and hide certain form fields based on previous user input. Currently works with checkbox inputs and select boxes.

How to use it:

1. Download and put the JavaScript file jquery.dependent.fields.js after jQuery JavaScript library.

<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="jquery.dependent.fields.js"></script>

2. This is a simple example that enables a checkbox to toggle several form fields when checked.

<label for="master-checkbox">
  Master Checkbox
</label>
<input id="master-checkbox" type="checkbox"/>

<label for="dependent-field1">
  Depends on Master 1
</label>
<input id="dependent-field1" class="depends-on-master-checkbox" type="text"/>

<label for="dependent-field2">
  Depends on Master 2
</label>
<input id="dependent-field2" class="depends-on-master-checkbox" type="text"/>

<label for="dependent-field3">
  Depends on Master 3
</label>
<input id="dependent-field3" class="depends-on-master-checkbox" type="text"/>
$('.depends-on-master-checkbox').dependsOn('#master-checkbox');

3. Here is another example shows how to show/hide form fields based on the previous option value.

<label for="master-dropdown">
  Master Dropdown
</label>
<select id="master-dropdown">
  <option value="">-- Select a Country --</option>
  <option value="Canada">Canada</option>
  <option value="France">France</option>
  <option value="Germany">Germany</option>
  <option value="United States">United States</option>
</select>

<label for="dependent-dropdown">
  Dependent Dropdown
</label>
<select id="dependent-dropdown">
  <option value="">-- Select a State / Territory --</option>
  <option value="Alabama">Alabama</option>
  <option value="Saskatchewan">Saskatchewan</option>
</select>
$('#dependent-dropdown').dependsOn('#master-dropdown', ['Canada', 'United States']);

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