Conditional Elements
Conditional elements are supported in HTML Forms by using two special attributes: data-show-if
and data-hide-if
.
Using these attributes allows you to hide or show parts of your form by referencing the name attribute of a field in your form.
For example, you could choose to only show the submit button after the email field is filled.
<input type="email" name="EMAIL" required />
<input type="submit" value="Send" data-show-if="EMAIL" />
Let’s do another example where you have a help text is hidden after someone starts typing in the field it describes.
<input type="text" name="NAME" />
<p data-hide-if="NAME">Enter your name in the field above.</p>
Specifying an Exact Value
The examples above will show or hide an element whenever the field that it is depending on contains any value, regardless of the actual value.
Sometimes you want to depend on an exact value though. This can be done by following the field name with a colon and the value you need, like this: NAME:VALUE
.
Let’s build a form with a list of checkboxes, where a message shows up only when one particular choice is selected.
<input type="checkbox" name="JOB" value="Marketeer" /> Marketeer
<input type="checkbox" name="JOB" value="Developer" /> Developer
<input type="checkbox" name="JOB" value="Recruiter" /> Recruiter
<div data-show-if="JOB:Recruiter">
Hi, recruiter!
</div>
Specifying Multiple Values
Continuing with the above example, what if you wanted to show part of your form for both developers and marketeers?
You can specify multiple expected values by separating them with a |
.
<input type="checkbox" name="JOB" value="Marketeer" /> Marketeer
<input type="checkbox" name="JOB" value="Developer" /> Developer
<input type="checkbox" name="JOB" value="Recruiter" /> Recruiter
<div data-show-if="JOB:Marketeer|Developer">
Hi, marketeer or developer!
</div>
Related Posts from Our Knowledge Base
Check out our collection of simple code snippets you can use to get the most out of HTML Forms on your WordPress websites.
HTML Forms comes with built-in form validation, but you can add your own as well with WordPress filters.