15

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user13955
  • 860
  • 2
  • 9
  • 25
  • 1
    Ya, you can use it outside any form if not using xhtml – A. Wolff Jul 09 '13 at 08:59
  • 1
    @roasted unless you're using some old browser (e.g. IE7 ignores `` outside of `
    `). And before you say that nobody uses them any more, note that most of the UK government computers have IE6 on them and there are no plans to upgrade.
    – Aleks G Jul 09 '13 at 09:03
  • @AleksG that's a good point! – A. Wolff Jul 09 '13 at 09:04
  • 2
    Possible duplicate of [Is well formed without a
    ?](http://stackoverflow.com/questions/3294572/is-input-well-formed-without-a-form)
    – Frédéric Hamidi Jul 09 '13 at 09:05

3 Answers3

14

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.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
6

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.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
2

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

HarryFink
  • 1,010
  • 1
  • 6
  • 6