user13955
user13955

Reputation: 870

Does a hidden input field have to be in a form?

I have a page where I need to store a value for processing via Ajax/jQuery. I'm using a hidden input field to store this value like this:

<input type="hidden" name="..." id="..." value="..." />

I can access this value through jQuery even if it is NOT in a form (ie: it's just at the start of my HTML output).

Question: even though it works, is it OK/legal to do from a correctness perspective to have a hidden input value which is not part of a form?

Upvotes: 16

Views: 13682

Answers (3)

OptimusCrime
OptimusCrime

Reputation: 14863

You can place hidden input-fields anywhere you want. Same goes for any other kind of input-fields (except submit). You can place buttons, select's etc without wrapping it in a form.

Note that if you submit a form, only the elements inside that form will be submitted.

I don't know what you plan to do with the hidden-inout, but if you are storing some sort of data from a script etc, I would recommend using the data-tag or indicate values by using classes/ids, or storing data as a js-variable. Having a bunch of hidden fields is not wrong, but I've always thought of it as an ugly solution.

Upvotes: 7

HarryFink
HarryFink

Reputation: 1010

Yes, you can have a valid input without a form.

Upvotes: 2

Kevin Bowersox
Kevin Bowersox

Reputation: 94479

You can place the hidden input outside of the form if you are retrieving the value for an ajax post with jquery. However, if your application must degrade (meaning work without javascript) you should have the hidden input in the form so it gets posted to the server on form submit.

Upvotes: 14

Related Questions