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 repoExamples
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:
- hideElementAnimation: the CSS class that will be added to the element before it is hidden
-
hideAnimationDelay: a delay in MS after which the element's
display
property will be set tonone
. This should be set to however long is your hiding CSS animation - showElementAnimation: the CSS class that will be applied to the element after it has been shown.
-
displayValue: the display value that should be applied to the
elements when they're being shown, for example
block
,flex
, etc.
After this you can add a show-if
attribute to
any element with the following syntax:
show-if="[element_to_check]=[value_to_check]"
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>
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
-
If an input has a
required
attribute, it will only show validation error if the input is visible, otherwise therequired
will be removed as long as the field is hidden, and added back once shown.