This is a quick how-to on showing/hiding form fields based on the input from a radio button set, a checkbox being checked, or an option from a select dropdown being chosen. You can do this for sites of any age, but this example relies on parsley being the most recent version with bootstrap 4. You can downgrade it if needed.
How To
HTML
For bootstrap 3/4 sites, make sure to include data-parsley-excluded=":hidden" on your form tag when showing/hiding things! It’ll validate only the things that are visible, so you can have required fields hidden without causing problems. They’ll only validate as required when they’re visible!
On your form, make sure to also set up the section that you want to hide/show. Wrap it in a div with a unique class or ID and target it in your script. Make sure to also include the d-none class on it–this will hide the section by default, and that d-none class will be removed as needed, as per your script.
Script - scripts.js
I find that the simplest way to target fields for uses like this is to use the name of the field. However this does require you to have a form that’s fully set up in the backend, so if it’s not there yet, feel free to add a class. Using the ID of the field won’t work because you’ll have different IDs for each radio button or checkbox.
Radio Buttons Set
$('input[name="jointAccount"]').on('click',function() {
if($(this).val() === "Yes") {
$('.joint-account-holder').removeClass('d-none');
} else if ($(this).val() === "No") {
$('.joint-account-holder').addClass('d-none');
}
});
Checkboxes
$('input[name="accountHolderInfo.mailingAddressDifferent"]').on('change',function() {
if(this.checked) {
$('.mailing-address-info').removeClass('d-none');
} else {
$('.mailing-address-info').addClass('d-none');
}
});
Select Dropdown
$('select[name="accountHolderInfo.mailingAddressDifferent"]').on('change',function() {
if($(this).val() === "Yes") {
$('.joint-account-holder').removeClass('d-none');
} else if ($(this).val() === "No") {
$('.joint-account-holder').addClass('d-none');
}
});
Example Sites
- Fifth District Savings Bank (Select dropdown variation. Under “How did you find us”, selecting “other” causes a new input field to appear)
Tags: form, bs2, bs3, bs4, script, js, javascript, jquery, html, parsley