Detected form widget conditional logic show hide fields: a build and test guide

Build safe show/hide field logic on an existing form after the Detected Form widget connects it: required-state handling, accessibility, validation, and a test…

James HollowayWeb Development Lead7 min read

Conditional logic on a form you already run seems trivial: pick a value, reveal a follow-up. In practice, detected form widget conditional logic show hide fields work fails in three places. A hidden control can still be submitted. A hidden required input still blocks submission. And a field that appears silently is invisible to screen reader users.

This is a build-and-test pass for an existing HTML form after the Detected Form widget connects it. The widget links your form to WidgetJar so submissions are captured; it does not rewrite your markup or your show/hide script. Everything below is standard HTML, CSS, JavaScript and accessibility work on your side, plus a repeatable test you run before launch.

What conditional logic changes on a form you already run

An HTML form is a request builder. The browser collects every successful control and sends name/value pairs to the endpoint in action, as the MDN guide to sending form data explains. That is why conditional logic bugs are mostly data bugs: a control still inside the form and still enabled can be sent even when nobody can see it.

Treat each conditional field as two separate states:

  • Visual state — is the wrapper shown or hidden?
  • Data state — will the control's value reach your endpoint, and does its required state match what is on screen?

Once the widget is connected, what gets captured depends on your field names, so keep existing name attributes exactly as they are. If fields arrive empty after the embed, that is a naming problem, not a logic problem — read name attribute missing submissions before you touch your show/hide code.

Decide the question first

Write a short state map before writing code. For each controlling field, list the dependents it reveals and the exact values that trigger them. Example: contact preference = "Phone" reveals a phone input; anything else hides it.

Also ask whether hiding is right at all. Use conditional logic for questions that are genuinely irrelevant in one branch, not to shorten a form by stealth. If a field only sometimes applies, a clarifying hint beside an always-visible field is often clearer than a reveal.

Keep these out of conditional hiding entirely:

  • Consent checkboxes. Consent that appears or disappears is ambiguous evidence. The consent checkbox guide covers keeping consent explicit on an existing form.
  • Privacy notices and data-use hints, which should stay visible whenever they are relevant.

Markup baseline: wrappers, labels, stable names

Put each conditional field in its own wrapper so you can toggle one block without disturbing neighbours:

<div class="field" data-conditional="phone" hidden>
  <label for="phone">Phone number</label>
  <input id="phone" name="phone" type="tel" autocomplete="tel" required>
</div>

Rules that prevent most later failures:

  1. Keep the control and its label in the DOM. Toggle the wrapper; do not inject markup on every change.
  2. Never rename fields. One stable name per input. Cloning a block is how duplicate names appear and overwrite each other in the submission.
  3. Keep ids unique. If you copy a block, update id, for and any aria-describedby references together.
  4. Keep hints and error text wired to the control, so they reappear attached when the field returns.

Show/hide mechanics that also fix submission

Two visual options do the same job with different side effects:

  • wrapper.hidden = true sets the hidden attribute. It is simple, but a stylesheet rule that sets display on the same element can override it, so audit your CSS.
  • A class toggle such as .is-hidden { display: none; } is explicit and easy to search for.

Either way, display: none removes the field from the tab order and from accessibility trees — which is what you want for a hidden block, provided you also handle the value and required state. Write the toggle as one function that always runs the same sequence:

function setConditional(wrapper, show) {
  const control = wrapper.querySelector('input, select, textarea');
  const status = document.getElementById('form-status');
  wrapper.hidden = !show;
  control.disabled = !show;
  if (show) {
    control.required = control.dataset.wasRequired === 'true';
  } else {
    control.dataset.wasRequired = String(control.required);
    control.required = false;
    control.setCustomValidity('');
  }
  status.textContent = show
    ? control.labels[0].textContent + ' field added.'
    : control.labels[0].textContent + ' field removed.';
}

Disabling the control while hidden is the cleanest way to stop a stale value reaching your endpoint, because disabled controls are not successful controls.

Required-state handling and native validation

The browser blocks submission when a required control is empty and reports the first invalid one. If a required input is hidden with display: none, the browser can still block submit and then try to focus an invisible field — a dead end where nothing seems to happen after the click. That is why the snippet restores required only on reveal. The MDN page on client-side form validation is explicit that required makes the form unsubmittable while the value is empty and that native messages appear on submission; you are borrowing that behaviour, so keep the attribute in sync with visibility.

Two more interplay points:

  • Read validation state after toggling. Use checkValidity() or the validity object on the control when you change state instead of caching results from page load.
  • Keep the required marker honest. If your label shows an asterisk, it must reflect the current state. The required field asterisk explainer covers the marker and native messaging together.
  • Clear custom messages on hide. A setCustomValidity message set while the field was visible lingers on the next reveal unless you reset it.

Accessibility: announce the change without stealing focus

A field that appears with no announcement is a dead end for screen reader users. Add a polite live region near the form and write a short sentence into it when state changes:

<p id="form-status" role="status" aria-live="polite"></p>

Keep the sentence specific ("Phone number field added") rather than generic. Focus behaviour matters just as much: do not move focus into a newly revealed field unless the user asked for it by selecting that option; jumping focus mid-form disorients keyboard users. Keep every visible control reachable in DOM order, and make the controller a real radio, select or checkbox with a visible label.

If the form lives inside a popup, the modal dialog pattern guidance sets out how focus entry, Tab containment and focus return should behave. Our accessible popup keyboard and focus checklist covers the form-level version of that test.

Autofill and stale values after a reveal

When a field is revealed late, browsers may still offer autofill, and a value typed before hiding can survive the round trip. Decide deliberately:

  • Keep meaningful autocomplete tokens (for example tel, email, postal-code) on fields that will be visible; they help rather than hurt.
  • The disabled state already keeps a hidden field out of the submission, so clear a value only if sending it later would be plainly wrong.
  • Re-test autofill after toggling, because some browsers re-offer saved values when a field appears. Our guide to native browser autofill overwriting values has a browser-by-browser test you can reuse.

A pre-launch test pass you can repeat

Run this on the live page after the widget is installed, once per branch of your logic:

  1. Tab-only walk with dependents hidden: reach every visible control, confirm a visible focus ring, and check that no hidden control receives focus.
  2. Reveal branch: select the triggering option with the keyboard, confirm the live region announces once, then complete and submit.
  3. Submit with dependents hidden: inspect the request payload in browser DevTools and confirm the hidden field is absent.
  4. Empty required field in the revealed branch: confirm the browser message appears on the visible field, not an invisible one.
  5. Toggle back and forth three times: check for duplicate ids, duplicate announcements and stale custom messages.
  6. Autofill check: trigger browser autofill, toggle the field, and confirm values are not silently overwritten.
  7. Screen reader spot check: with one screen reader, confirm the announcement fires once per change and the label is read with the control when it appears.

Keep the state map in the repository next to the form so the next person changing a field knows what controls what.

Ship checklist

  • State map documented: controller, trigger values, dependents.
  • Every conditional field wrapped, labelled and uniquely named.
  • disabled and required toggled together with visibility.
  • Custom validity messages cleared on hide.
  • Live region tested in one screen reader; polite, no focus stealing.
  • One clean submission tested per branch, with the payload inspected.
  • Consent checkboxes reviewed for visibility and explicit opt-in.
  • Autofill re-tested on the browsers your visitors actually use.

When the logic is stable, connect the form with the Detected Form widget and run this test pass on the page where the embed lives before you send traffic to it.

  • detected form widget conditional logic show hide fields
  • forms
  • validation
  • accessibility
  • detected form

Written by

James Holloway

Web Development Lead at WidgetJar

Keep reading

Get started

Your next lead is one line away.

Pick a design, make it yours and paste a single script tag. Every widget type is included, and you do not need a credit card to start.

<script src="https://cdn.widgetjar.com/wj-assets/embed.js" defer></script>