What’s the point of having hidden input in HTML? What are common uses for this?

They’re used to pass data that will be needed when the form is submitted. One of the more common cases would be a form allowing users to edit some existing entry. You’ll need to know which entry they’re editing so that you can update the correct row in the database when they submit the form. The user doesn’t need to edit (or even know) the ID of the entry though, so a hidden field works well here.

Other options

URL parameters:
This could also be done by building the parameters into the url that the form is being submitted to:

<form action="save.php?entry_id=1234">

but this means you have to handle building the URL properly and escaping the data yourself, and the length of URLs servers will accept is limited so it may not work for longer data. So generally using hidden form fields is the easier way to go.

Session variables: When the edit page loads you’d store the entry ID in a session variable, and then retrieve it on the page that saves the changes. That’s a lot easier to mess up though; setting up and maintaining sessions may require adding code in several different places, and then their session could expire in between loading and saving, and you have to make sure it works if they have multiple windows or tabs open, and you have to make sure it doesn’t do weird things when they hit back/forward. Because of all these potential pitfalls it isn’t a great way to solve this problem–passing the id with the data being submitted is a lot more robust.

Cookies: In many languages/frameworks sessions are tracked using cookies, so they’re basically the same solution. The pitfalls are the same as for session variables even when sessions are tracked by other methods though.

Leave a Comment