Conditional Fields

Conditional Fields is a vanilla JS library that allows you to hide/show form fields conditionally depending on the value of some other field.

GitHub repo

Examples

Setup

To set up, simply download the ConditionalFields.js file and include it in your project via <script> tag.

Usage

To use the library, create an instance of ConditionalFields that was included when setting up. Make sure the instance is created After the elements have been added to the DOM.

As the argument to the ConditionalFields, you can pass a single optional options object with the following optional properties:

After this you can add a show-if attribute to any element with the following syntax:

show-if="[element_to_check]=[value_to_check]"
Where element_to_check is the ID of the element whose value will be checked, and value_to_check being the value to check for. Whenever the element's value changes to the specified value, the element with the show-if attribute will be shown. Otherwise it will be hidden.

For example:

<div show-if="email=some@mail.com"></div>
Now whenever an input with ID email has its value set to some@mail.com, the div will be shown.

If element_to_check is a checkbox, then you can omit the '=' sign and anything after it.

Notes