0

Let's say I have a form like this:

<form id="something_form">
  <input type="text" id="thing1" name="thing1">
  <input type="hidden" id="thing2" name="thing2">
  <input type="text" id="secret" name="secret">

  <input type="submit">
</form>

Currently I have JS that listens for the submission event, takes the info in the secret input, and does some work before adding it to thing2. The server never uses or needs secret. I can clear the data in secret before form submission, so it's just thing1=abc&thing2=abc&secret=, however if the user has JS off, then the form submission request would have thing1=abc&thing2=&secret=secret.

Is there a pure HTML way to make an input work as normal, but not get serialized/submitted on form submission? I know that I can remove name="secret" to achieve this, but that loses me any functionality that relies on the name attribute.

My idea for a solution is to render the page without the name="secret":

<input type="text" id="secret">

then add it via JS(since if the user has JS on, it would run):

document.getElementById("secret").setAttribute("name", "secret");

But I'm curious if there's another solution for this.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Peter R
  • 3,185
  • 23
  • 43

1 Answers1

2

One option is to use the form attribute. An input with the form attribute set counts as part of the form whose ID matches its form attribute, NOT as part of the form that it's actually inside of.

Example: <input type="text" name="fish" form="bogus"> won't get submitted along with the rest of the form, unless the form has id="bogus" for some reason.

Brilliand
  • 13,404
  • 6
  • 46
  • 58
  • 1
    One comment on the linked duplicate did mention that this is (or was) invalid HTML. That's probably not a practical concern, but you might also look at omitting the name attribute, which apparently accomplishes the same goal. – isherwood Dec 10 '21 at 21:21
  • 1
    Omitting the `name` entirely causes issues with existing JS libs I'm using, which is why I thought rendering without `name` attr, but adding the `name` attr on page load via JS would solve it, but I usually prefer a non-JS solution if possible. So this is much better than my solution. – Peter R Dec 10 '21 at 21:25