Ask Anvil

Answers to questions about automating PDFs, e-signatures, Webforms, and other paperwork problems.
Webforms
Categories

How do I pre-fill a web form from URL query parameters?

function prefillForm(form, search = window.location.search) {
  const params = new URLSearchParams(search);

  for (const name of new Set(params.keys())) {
    const values = params.getAll(name);
    const fields = Array.from(form.elements).filter((el) => el.name === name);
    if (fields.length === 0) continue; // ignore params the form doesn't have

    for (const field of fields) {
      if (field.type === 'checkbox' || field.type === 'radio') {
        field.checked = values.includes(field.value);
      } else if (field.type === 'file' || field.type === 'password') {
        continue; // never prefill these
      } else if (field.tagName === 'SELECT' && field.multiple) {
        for (const option of field.options) {
          option.selected = values.includes(option.value);
        }
      } else {
        field.value = values[0];
      }
    }
  }
}

Call it once after the form exists in the DOM, for example prefillForm(document.querySelector('form')). A link like /apply?full_name=Ada%20Lovelace&state=NY&plan=pro&tags=x&tags=y fills a text input, a select, a radio group, and two checkboxes.

Why it works this way

URLSearchParams decodes percent-encoding for you, and getAll() returns every value for a repeated key, which is how multiple checkboxes or a multi-select arrive. form.elements lists every control in the form, so matching on the name attribute works for inputs, selects, and textareas alike. Checkboxes and radios are set through checked, not value, because their value is the string submitted when they are selected.

Caveats

Do not put sensitive data in the URL. Query strings end up in browser history and server access logs, so names and plan choices are fine, but SSNs, account numbers, and tokens are not. If you need to carry private data into a form, look it up server side from an opaque ID instead.

Treat query values as untrusted input. Assigning to value or checked is safe, but never write a parameter into the page with innerHTML. Prefilled values also need the same server-side validation as typed ones, since anyone can edit the link or the field before submitting.

Back to All Questions

The fastest way to build software for documents

Anvil Document SDK is a comprehensive toolbox for product teams launching document flows where PDF filling, signing, and complex conditional scenarios are necessary.
Explore Anvil
Anvil Webforms
Marketing Mode