Skip to content
Advertisement

Conditional Form Inputs – Multiple Fields Shown/Hidden

I am attempting to build a form that hides multiple input boxes of the form unless a condition is met.
So the question would be: Do you have a separate mailing address? Yes No

If “yes” is selected, I want to then show three input fields for their mailing address, city, and zip. If “no,” then I don’t want anything to show up. I’d just like them to be able to go to the next line.

What I’ve come up with so far from research only works if I do a simple single input box for a response. When I attempt to do multiple inputs within their own divs, it breaks the form.

JavaScript
JavaScript

Thank you.

Advertisement

Answer

I have a lot of comments here that hopefully can help you:

  1. A <fieldset> can be used in a form for handling a group of form fields. If it has the disabled attribute all child form fields will be disabled.
  2. In your case the radio buttons can have the values 0 and 1. These values can be turned into a boolean.
  3. The attribute in <input> can have any value, but try to stick to the standards: autocomplete #values.
  4. Try to make use of the name attribute in forms and use less IDs — IDs need to be unique in the HTML document.
  5. Instead of using a class name like “required-text” in your case for styling required fields, use the required attribute and style according to that.

The JavaScript listens for a change event on the entire form (so, this could be any change on any form field). I test if the e.target.name is “yesOrNo” — then I know that the radio buttons changed. Now I can take the boolean value from the “radioNodeList” and assign that to the disabled property of the fieldset.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement