The Switch Behavior Explained
Update: Comments are closed for this post, but you can go to the wForms forum if you have any question or comment. Thanks !
This post is part of the wForms Documentation. wForms is an open-source javascript library that adds commonly needed behaviors to traditional web forms without the need for any programming skill.
For additional help, visit the wForms forum.
The Switch behavior tackle one of the most common problem in web forms: How to display only the relevant parts of a form and hide the rest.
Let’s say I want you to subscribe to my imaginary newsletter. I need:
- Your agreement
- Your email
But it doesn’t make sense to ask for your email address if you don’t want the newsletter in the first place, right ? With the Switch behavior I can ask for your email only if you check the ‘I want to…’ box.
Go ahead, check the box:
It’s time for some definitions:
- The switch is the checkbox.
The switch operates on a target which can be turned on and off. - The target is the email input field.
The target is visible only when the switch is activated. - Since you can have several switches and targets on one page, we need to identify a switch and its target(s) by name. For example ‘NewsletterOptin’.
Now let’s implement our Switch in 3 small steps .
- Enable the wForms extension by adding the following code to the <head> element of your page:
<script type="text/javascript" src="wforms.js" ></script> - Add the ’switch-NewsletterOptin’ class to your checkbox.
<input type="checkbox" ... class="switch-NewsletterOptin" /> - Add the ‘offstate-NewsletterOptin’ class to your target. Because the target is actually the input field and the label, we need to nest them within a div.
<div class='offstate-NewsletterOptin‘><label … > … </label> <input … /></div>
The switch is now operational, but we are not done yet.
What happens behind the scene is really simple. When you check the box, the div class turns to ‘onstate-NewsletterOptin‘.
How this visually affects the form really depends on your CSS. If you want the show/hide effect, add these 2 rules to your stylesheet.
.offstate-NewsletterOptin { display: none; }
.onstate-NewsletterOptin { display: block; }
If you want the switch to have a different kind of effect, just change your CSS.
That’s all folks.
Note: The name ‘NewsletterOptin’ is just an example. You can use anything as long as you are consistent: ’switch-somename’, ‘offstate-somename’, ‘onstate-somename’. If you use the form builder you will only get to choose a letter between A and K.
Update: Comments are now closed for this post, but you can go to the wForms forum if you have any question or comment. Thanks !