Chapter 11 of 26

Forms

So far, every page we have built only shows information to the visitor. Headings, paragraphs, links, images, lists and tables all flow in one direction: from the website to the reader.

But think about what you actually do on the web every day: you log in, search for a train, apply for an exam, post a comment, upload a photo, pay a bill. All of these need the visitor to send information back to the website.

In HTML, that two-way conversation happens through forms. In this chapter we will learn how a form is built, how the browser packages the data, and which elements you use for text boxes, drop-downs and buttons.

What is an HTML Form?

An HTML form is a section of a page, created with the <form> element, that groups together controls (text boxes, check boxes, drop-downs, buttons) so that the values the user enters can be submitted to a server for processing.

A form has three parts working together:

  • Controls – the boxes and buttons the user interacts with (<input>, <textarea>, <select>, <button>).

  • Labels – text that tells the user (and screen readers) what each control is for.

  • The form element itself – which decides where the data goes and how it is sent.

Here is the journey of the data:

 User fills the form
        ↓
 Clicks "Submit"
        ↓
 Browser collects every control that has a name
 and turns it into  name=value  pairs
        ↓
 Browser sends an HTTP request (GET or POST) to the URL in "action"
        ↓
 Server program (PHP, Node.js, Java, Python ...) reads the pairs,
 does its work, and sends back a new page

Notice an important point: HTML only collects and sends the data. Saving it in a database, checking a password or sending an email is the job of a server-side program. HTML forms are the front door; the server is the house.


Your First Form

Let's build a small "Contact Us" form and then take it apart piece by piece.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Contact Us</title>
</head>
<body>
  <h1>Contact Us</h1>

  <form action="/contact" method="post">
    <p>
      <label for="name">Your name</label>
      <input type="text" id="name" name="name">
    </p>
    <p>
      <label for="email">Email</label>
      <input type="email" id="email" name="email">
    </p>
    <p>
      <label for="msg">Message</label><br>
      <textarea id="msg" name="message" rows="4" cols="40"></textarea>
    </p>
    <button type="submit">Send</button>
  </form>
</body>
</html>

When you open this file in a browser you see a heading "Contact Us", two single-line text boxes labelled "Your name" and "Email", a larger multi-line box labelled "Message", and a "Send" button. Clicking on the word "Your name" puts the cursor inside the name box – that is the label doing its job.

When the user types Asha, asha@example.com and Hi there and presses Send, the browser sends a POST request to /contact whose body looks like this:

name=Asha&email=asha%40example.com&message=Hi+there

Look carefully at that line, because it explains almost everything about forms:

  • Each control becomes a name=value pair. The name comes from the name attribute, the value is what the user typed.

  • Pairs are joined with &.

  • Special characters are encoded: a space becomes + and @ becomes %40. This is called URL encoding (percent-encoding).


The <form> Element and Its Attributes

The <form> element wraps all the controls. Its most important attributes are:

Attribute

What it does

Default

action

The URL that will receive the data

The current page's URL

method

How to send it: get, post (or dialog, used only inside a <dialog>)

get

enctype

How POST data is encoded

application/x-www-form-urlencoded

target

Where to show the response (_self, _blank ...)

_self

autocomplete

Whether the browser may auto-fill saved values (on / off)

on

novalidate

Turns off the browser's built-in checks on submit

Not set (validation on)

We will meet novalidate properly in the chapter Built-in Form Validation.

GET vs POST

This is one of the most asked interview questions on forms, so let's understand it clearly.

With GET, the data is attached to the end of the URL after a ?:

<form action="https://www.example.com/search" method="get">
  <label for="q">Search</label>
  <input type="search" id="q" name="q">
  <button type="submit">Go</button>
</form>

Typing html forms and clicking Go takes the browser to:

https://www.example.com/search?q=html+forms

With POST, the data travels inside the body of the HTTP request, so the URL stays clean (/contact in our first example).

Point

GET

POST

Where data goes

In the URL (query string)

In the request body

Visible in address bar / history

Yes

No

Can be bookmarked or shared

Yes

No

Size

Limited by practical URL length limits of browsers and servers

Suitable for large data

File uploads

Not possible

Possible (with multipart/form-data)

Meaning

"Fetch something" – should not change data on the server

"Do something" – create, update, send

Typical use

Search boxes, filters

Login, sign-up, payment, comments

Rule of thumb: if submitting the form only reads data (search, filter), use GET. If it changes something or contains private data (passwords), use POST.

A common misconception: POST is not "secure" by itself. It only keeps the data out of the URL. Anyone watching the network can still read it unless the site uses HTTPS, which encrypts the whole request.

The enctype Attribute

enctype matters only when method="post". It has three possible values:

Value

When to use

application/x-www-form-urlencoded

Default. Plain text fields, encoded as name=value&...

multipart/form-data

Required when the form uploads files (<input type="file">)

text/plain

Only for debugging; not reliable for real processing


The name Attribute: The Most Important One

Beginners often build a beautiful form, submit it, and find that the server received nothing. Ninety percent of the time the reason is a missing name.

Only controls that have a name attribute are submitted. The id is for labels, CSS and JavaScript; the name is the key the server sees.

<!-- Sent as  city=Delhi -->
<input type="text" id="city" name="city" value="Delhi">

<!-- NOT sent at all: no name -->
<input type="text" id="pin" value="110001">

The value attribute on a text box sets its initial value. Once the user edits the box, the submitted value is whatever is in the box at that moment.


Labels: Connecting Text to Controls

A label tells the user what to type. You could just write plain text next to an input, but a real <label> gives three big advantages:

  1. Bigger click area – clicking the label focuses the input (or ticks the check box). Very helpful on phones.

  2. Accessibility – screen readers announce the label when the input gets focus. Without it, a blind user just hears "edit text".

  3. Clear structure – the browser knows which text belongs to which control.

There are two ways to connect a label:

Method 1: Explicit label with for and id

<label for="phone">Mobile number</label>
<input type="tel" id="phone" name="phone">

The label's for must exactly match the input's id (not its name).

Method 2: Implicit label (wrapping)

<label>
  Mobile number
  <input type="tel" name="phone">
</label>

Both are valid. The explicit method is more flexible for layouts (label and input can be in different places) and is the most widely understood by assistive technologies, so many teams use it by default.

A placeholder (grey hint text inside a box) is not a replacement for a label. It disappears as soon as the user starts typing, and it is often low-contrast.


The <input> Element

<input> is the most-used form control. It is a void element (no closing tag), and its behaviour changes completely depending on its type attribute:

<input type="text" name="username">
<input type="password" name="pwd" autocomplete="current-password">
<input type="checkbox" name="agree" value="yes">

If you leave out type, or write a type the browser doesn't know, you get type="text". There are over twenty types – email, number, date, range, file, colour and more – and they get a full chapter of their own: Input Types. In this chapter we stay with plain text and password.

type="password" simply hides the characters on screen with dots. The value is still sent as normal text – which is why login forms must use POST over HTTPS.


Multi-line Text: <textarea>

For longer text – an address, a comment, a complaint – use <textarea>:

<label for="addr">Postal address</label><br>
<textarea id="addr" name="address" rows="3" cols="30">Flat 12, MG Road</textarea>

Things to remember about <textarea>:

  • It has a closing tag. The text between the tags is the initial value. It does not have a value attribute.

  • rows and cols set the visible size in lines and characters (CSS is usually used for this in real sites).

  • Whitespace between the tags counts. Writing the closing tag on a new line with indentation puts those spaces into the box. (The only exception: a single line break written immediately after the opening <textarea> tag is ignored by the parser.)

  • maxlength limits how many characters can be typed.


When the user must choose from a fixed list – state, branch, semester – a drop-down saves space and prevents spelling mistakes.

<label for="branch">Branch</label>
<select id="branch" name="branch">
  <option value="">-- Select branch --</option>
  <option value="cse">Computer Science</option>
  <option value="ece" selected>Electronics</option>
  <option value="me">Mechanical</option>
</select>

Here the drop-down shows "Electronics" initially because of selected. If the user leaves it unchanged, the server receives branch=ece – the value, not the visible text. If an <option> has no value attribute, its text content is sent instead.

Grouping options with <optgroup>

<label for="city">City</label>
<select id="city" name="city">
  <optgroup label="Maharashtra">
    <option>Mumbai</option>
    <option>Pune</option>
  </optgroup>
  <optgroup label="Karnataka">
    <option>Bengaluru</option>
    <option>Mysuru</option>
  </optgroup>
</select>

The group names appear as bold, non-selectable headings inside the list.

Choosing many: multiple

<select name="skills" multiple size="4">
  <option>HTML</option>
  <option>CSS</option>
  <option>JavaScript</option>
  <option>SQL</option>
</select>

With multiple, the list is shown as a box (size = number of visible rows) and the user can pick several items with Ctrl/Cmd-click. Each chosen item is sent as a separate pair: skills=HTML&skills=SQL. Because many users don't know the Ctrl-click trick, a group of check boxes is often friendlier.


Buttons

A form needs a way to be submitted. The modern way is the <button> element:

<button type="submit">Register</button>
<button type="reset">Clear</button>
<button type="button">Show help</button>

type

What happens on click

submit

Submits the form (this is the default when type is missing)

reset

Restores every control to its initial value

button

Does nothing by itself – used with JavaScript

That default is a classic bug: a <button> meant to "show password" inside a form, written without type="button", submits the form every time it is clicked.

<button> vs <input type="submit">

You will also see the older style:

<input type="submit" value="Register">

Both submit the form. The difference is that <input> is a void element, so its text can only come from the value attribute, while <button> can contain other HTML such as an icon plus text. That flexibility is why <button> is preferred today.

Pressing Enter inside a single-line text field also submits the form, using its first submit button (this is called implicit submission).


Long forms become easier to understand when related fields are grouped. <fieldset> draws a box around a group and <legend> gives it a caption.

<form action="/apply" method="post">
  <fieldset>
    <legend>Personal details</legend>
    <p>
      <label for="fname">Full name</label>
      <input type="text" id="fname" name="fullname">
    </p>
    <p>
      <label for="dob">Date of birth</label>
      <input type="date" id="dob" name="dob">
    </p>
  </fieldset>

  <fieldset>
    <legend>Course</legend>
    <p>
      <label for="course">Programme</label>
      <select id="course" name="course">
        <option>B.Tech</option>
        <option>BCA</option>
        <option>MCA</option>
      </select>
    </p>
  </fieldset>

  <button type="submit">Apply</button>
</form>

In the browser each group appears inside a thin grey border with its legend ("Personal details", "Course") sitting on the top edge of the border.

Screen readers read the legend along with each field inside the group, which is especially important for groups of radio buttons such as "Gender" or "Payment method" – you'll see this in the next chapter. A disabled attribute on a <fieldset> disables every control inside it at once.


disabled vs readonly

Both stop the user from editing a field, but they behave differently:

<input type="text" name="roll" value="21CS045" readonly>
<input type="text" name="fee" value="50000" disabled>

Point

readonly

disabled

User can edit

No

No

Can be focused / text selected

Yes

No

Value submitted

Yes

No

Looks greyed out

No (by default)

Yes

Works on

Text-like inputs (text, search, email, url, tel, password, number, date/time types) and <textarea> – not check boxes, radios or <select>

All controls, and <fieldset>

So in the code above, the server receives roll=21CS045 but nothing for fee.

Never trust readonly or disabled for security. A user can change or re-enable fields with the browser's developer tools. The server must always re-check important values.


Worked Example: What Exactly Gets Submitted?

This is the kind of question that tests real understanding. Look at this form:

<form action="/register" method="get">
  <input type="text" name="user" value="ravi kumar">
  <input type="text" name="nick" value="rk" disabled>
  <input type="text" value="no name here">
  <input type="checkbox" name="news" checked>
  <input type="checkbox" name="sms">
  <select name="city">
    <option>Pune</option>
    <option value="BLR" selected>Bengaluru</option>
  </select>
  <button type="submit" name="action" value="save">Save</button>
</form>

The user clicks Save without changing anything. Let's go control by control:

  1. user – has a name, enabled → user=ravi+kumar (space encoded as +).

  2. nick – disabled → skipped.

  3. Third input – no name → skipped.

  4. news – checked, but no value attribute → the browser sends the default value on: news=on.

  5. sms – unchecked → skipped (unchecked boxes send nothing at all).

  6. city – selected option's value → city=BLR.

  7. The button – a named submit button is included only if it was the one clicked → action=save.

Final URL:

/register?user=ravi+kumar&news=on&city=BLR&action=save

Controls Outside the Form: the form Attribute

Normally a control belongs to the <form> that contains it. Sometimes the layout forces a button or input to sit elsewhere on the page. You can still connect it using the form attribute, which takes the form's id:

<form id="signup" action="/signup" method="post">
  <label for="mail">Email</label>
  <input type="email" id="mail" name="email">
</form>

<!-- somewhere else on the page -->
<button type="submit" form="signup">Create account</button>

A Complete Example

Let's put everything together in an exam registration form.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Exam Registration</title>
</head>
<body>
  <h1>Semester Exam Registration</h1>

  <form action="/register" method="post">
    <fieldset>
      <legend>Student</legend>
      <p>
        <label for="sname">Name</label>
        <input type="text" id="sname" name="name" autocomplete="name">
      </p>
      <p>
        <label for="roll">Roll number</label>
        <input type="text" id="roll" name="roll" value="21CS045" readonly>
      </p>
    </fieldset>

    <fieldset>
      <legend>Exam</legend>
      <p>
        <label for="sem">Semester</label>
        <select id="sem" name="semester">
          <option value="5">5th</option>
          <option value="6" selected>6th</option>
        </select>
      </p>
      <p>
        <label for="remarks">Remarks (optional)</label><br>
        <textarea id="remarks" name="remarks" rows="3" cols="40"></textarea>
      </p>
    </fieldset>

    <button type="submit">Register</button>
    <button type="reset">Clear</button>
  </form>
</body>
</html>

Output in the browser: the heading, then a bordered box captioned "Student" containing the Name box and a Roll number box already filled with 21CS045, then a second box captioned "Exam" with a Semester drop-down showing "6th" and a Remarks text area, and finally the Register and Clear buttons.

The form looks plain because we haven't used any CSS – styling forms is a CSS topic. The structure is what HTML is responsible for, and this structure is correct and accessible.


Form Elements at a Glance

Element

Purpose

Closing tag?

<form>

Container; decides where and how data is sent

Yes

<label>

Caption for a control

Yes

<input>

Single-line field, check box, radio, etc. (by type)

No (void)

<textarea>

Multi-line text

Yes

<select> / <option> / <optgroup>

Drop-down or list box

Yes

<button>

Submit, reset or custom button

Yes

<fieldset> / <legend>

Group related controls with a caption

Yes


Common Mistakes

  • Forgetting name. The field shows up on screen but is never sent.

  • Matching for to name instead of id. The label must point to the id.

  • Using GET for passwords. The password ends up in the address bar, browser history and server logs.

  • Forgetting enctype="multipart/form-data" for file uploads. Only the file name reaches the server, not the file.

  • A <button> without type used for JavaScript actions. It submits the form by accident.

  • Using disabled when you want the value sent. Use readonly instead.

  • Nesting a <form> inside another <form>. This is not allowed; the inner form tag is ignored by the parser. Use the form attribute instead.

  • Using placeholder text as the only label.


Interview Questions

1. What is the default method of a form, and where does the data go?

The default is get. The data is appended to the action URL as a query string, e.g. ?q=html&page=2. If action is missing, the form submits to the current page's URL.

2. Why is a form field's value not reaching the server?

The most likely causes: the control has no name attribute, it is disabled (or inside a disabled <fieldset>), it is an unchecked check box or radio button, or it is outside the <form> without a form="id" attribute.

3. What is the difference between id and name on an input?

id must be unique in the page and is used by <label for>, CSS and JavaScript. name is the key used when the form data is submitted; several controls can share a name (for example, a radio button group).

4. Is POST more secure than GET?

Only slightly: POST keeps data out of the URL, history and logs. But the data is not encrypted. Real protection comes from HTTPS, and from validating everything on the server.

5. What will this send when the box is ticked: <input type="checkbox" name="tnc">?

tnc=on, because a check box with no value attribute uses on as its value. If it is not ticked, nothing is sent.

6. Which enctype is needed for file upload and why?

multipart/form-data. The default URL-encoded format can only carry text pairs; multipart splits the body into separate parts so binary file content can be sent along with the other fields.


Conclusion

Forms are how a web page collects information from the user and sends it to a server.

<form action="URL" method="get | post">   → where and how
  <label for="x">                          → what the field means
  <input name="x"> <textarea> <select>     → the controls
  <button type="submit">                   → sends everything
</form>

Data sent = name=value pairs of every named, enabled, "successful" control
  • Use GET for searches, POST for anything that changes data or is private.

  • Every control that should be sent needs a name; every control should have a <label>.

  • <button> submits by default – add type="button" for non-submitting buttons.

  • Group related fields with <fieldset> and <legend>.

  • readonly values are sent; disabled values are not.

In the next chapter, Input Types, we'll explore the many flavours of <input> – email, number, date, check boxes, radio buttons, file uploads and more.