HTML Form

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 6 Examples + 6 Try It
form / label / submit

Introduction

HTML forms are the primary way websites collect information from users—contact messages, logins, surveys, and search queries all start with a <form> element wrapping interactive controls.

This tutorial covers form structure, attributes, validation, submission, JavaScript handling with FormData, common mistakes, and six hands-on examples you can edit in the Try It editor.

What You’ll Learn

01

form

Container.

02

label

Accessible.

03

action

Send data.

04

validate

required.

05

submit

POST / GET.

06

FormData

Read in JS.

What Is an HTML Form?

An HTML form is a section of a document that contains controls where users enter or choose data. When the form is submitted, the browser gathers values from named fields and sends them to a destination URL or passes them to JavaScript.

Forms connect the front end to server-side scripts, APIs, or client-side logic. Every control that should contribute data needs a name attribute, and accessible forms pair each input with a <label>. See the form tag reference for the full attribute list.

💡
Beginner Tip

All inputs, textareas, selects, and submit buttons must be inside the <form> element. Closing the form too early leaves controls outside and breaks submission.

Form Elements

A typical form combines several HTML elements, each with a specific role:

  • <form> — wraps all controls and defines where data goes.
  • <label> — describes a field; link it with for matching the input’s id.
  • <input> — single-line fields (text, email, password, etc.).
  • <textarea> — multi-line text entry.
  • <button> — triggers submission or other actions.

Here is a complete contact form with all core elements nested correctly:

html
<form>
  <label for="name">Name</label>
  <input type="text" id="name" name="name">

  <label for="email">Email</label>
  <input type="email" id="email" name="email">

  <label for="message">Message</label>
  <textarea id="message" name="message" rows="4"></textarea>

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

Learn more about individual controls in the HTML Inputs tutorial and the textarea and button tag references.

Form Attributes

The <form> element itself accepts attributes that control submission behavior:

action

The URL where form data is sent when submitted. If omitted, the current page URL is used.

html
<form action="/submit" method="post">
  <!-- fields -->
</form>

method

How data is sent. get appends values to the URL; post sends them in the request body (preferred for sensitive data).

html
<form action="/search" method="get">
  <input type="search" name="q">
  <button type="submit">Search</button>
</form>

enctype

Sets the encoding type. Use multipart/form-data when uploading files; otherwise the default application/x-www-form-urlencoded is fine.

html
<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="photo">
  <button type="submit">Upload</button>
</form>

name

Identifies the form for scripting or when multiple forms exist on one page. Rarely required for basic sites but useful in complex apps.

html
<form name="loginForm" action="/login" method="post">
  <!-- fields -->
</form>

Form Validation

HTML5 provides built-in validation attributes on inputs. The browser checks values before allowing submission:

  • required — field must not be empty.
  • pattern — value must match a regular expression.
  • min / max — bounds for numbers and dates.
  • typeemail, url, and number add format checks.

Keep all validated fields inside the form. Closing </form> before inputs breaks both layout and validation:

html
<form>
  <label for="username">Username</label>
  <input type="text" id="username" name="username"
    required pattern="[A-Za-z]{5,}" title="At least 5 letters">

  <label for="age">Age</label>
  <input type="number" id="age" name="age" min="1" max="100" required>

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

Client-side validation improves UX but is not secure. Always re-validate on the server.

Form Submission

When the user clicks a submit button or presses Enter in a text field, the browser sends the form data to the action URL using the specified method.

The submit button must be inside the form. A button placed after </form> will not submit the form:

html
<form action="/submit" method="post">
  <label for="email">Email</label>
  <input type="email" id="email" name="email" required>

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

Use type="button" for buttons that should not submit (e.g. “Cancel” or “Add row”). Only type="submit" (the default for <button> inside a form) triggers submission.

Handling Form Data

JavaScript can intercept submission, read values without a page reload, and send data to an API. Use FormData to collect all named fields:

js
const form = document.getElementById("contactForm");

form.addEventListener("submit", function (event) {
  event.preventDefault();

  const data = new FormData(form);
  console.log("Name:", data.get("name"));
  console.log("Email:", data.get("email"));

  // Send to server with fetch(data) or display a success message
});
  • event.preventDefault() — stops the browser from navigating away.
  • new FormData(form) — reads all named controls in one object.
  • data.get("name") — retrieves a single field value by name.

Common Pitfalls

  • Missing name — fields without name are excluded from submission data.
  • Closing form too early — inputs or buttons outside <form> are not submitted.
  • No labels — placeholders are not substitutes; use <label for="id">.
  • Client-only validation — always validate again on the server for security.
  • Wrong enctype — file uploads need multipart/form-data.
  • Multiple submit buttons — only the clicked button’s name/value is sent; plan accordingly.

Examples Gallery

Six examples from a basic contact form to a complete page with JavaScript handling. Each includes View Output and Try It Yourself.

Example 1 — Basic Contact Form

html
<form>
  <label for="name">Name</label>
  <input type="text" id="name" name="name">

  <label for="email">Email</label>
  <input type="email" id="email" name="email">

  <label for="message">Message</label>
  <textarea id="message" name="message" rows="4"></textarea>

  <button type="submit">Submit</button>
</form>
Try It Yourself

How It Works

The form wraps labels, inputs, textarea, and submit button. Each field has matching id and for attributes plus a name for submission.

Example 2 — action + method post

html
<form action="/submit" method="post">
  <label for="username">Username</label>
  <input type="text" id="username" name="username" required>

  <label for="password">Password</label>
  <input type="password" id="password" name="password" required>

  <button type="submit">Log in</button>
</form>
Try It Yourself

How It Works

action sets the destination URL; method="post" sends credentials in the request body instead of the URL bar.

Example 3 — Validation (required, pattern, min, max)

html
<form>
  <label for="username">Username</label>
  <input type="text" id="username" name="username"
    required pattern="[A-Za-z]{5,}" title="At least 5 letters">

  <label for="age">Age</label>
  <input type="number" id="age" name="age" min="1" max="100" required>

  <button type="submit">Register</button>
</form>
Try It Yourself

How It Works

Try submitting with fewer than five letters or an age outside 1–100—the browser blocks submission and shows a message.

Example 4 — Select Dropdown

html
<form>
  <label for="course">Choose a course</label>
  <select id="course" name="course" required>
    <option value="">-- Select --</option>
    <option value="html">HTML Basics</option>
    <option value="css">CSS Styling</option>
    <option value="js">JavaScript</option>
  </select>

  <label for="enroll-email">Your email</label>
  <input type="email" id="enroll-email" name="email" required>

  <button type="submit">Enroll</button>
</form>
Try It Yourself

How It Works

<select> presents a dropdown. The selected option’s value is sent under the select’s name.

Example 5 — Fieldset, Radio, and Checkbox

html
<form>
  <fieldset>
    <legend>Experience level</legend>
    <input type="radio" id="beginner" name="level" value="beginner">
    <label for="beginner">Beginner</label>
    <input type="radio" id="advanced" name="level" value="advanced">
    <label for="advanced">Advanced</label>
  </fieldset>

  <input type="checkbox" id="newsletter" name="newsletter" value="yes">
  <label for="newsletter">Email me updates</label>

  <button type="submit">Send survey</button>
</form>
Try It Yourself

How It Works

fieldset groups related controls visually and for assistive tech. Radios share a name so only one is selected; checkboxes are independent.

Example 6 — Complete Contact Form with FormData

Full page with validation and JavaScript that reads submitted values via FormData:

html
<form id="contactForm" action="/submit" method="post">
  <label for="name">Name</label>
  <input type="text" id="name" name="name" required>

  <label for="email">Email</label>
  <input type="email" id="email" name="email" required>

  <label for="message">Message</label>
  <textarea id="message" name="message" rows="5" required></textarea>

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

<script>
  document.getElementById("contactForm").addEventListener("submit", function (e) {
    e.preventDefault();
    const data = new FormData(this);
    console.log("Name:", data.get("name"));
  });
</script>
Try It Yourself

How It Works

JavaScript intercepts submit, builds FormData, and shows a success message without reloading the page. Open Try It to see the full script.

Best Practices

✅ Do

  • Give every submittable control a name attribute
  • Pair inputs with <label for="id">
  • Keep all fields and submit buttons inside <form>
  • Use method="post" for sensitive data
  • Validate on both client and server

❌ Don’t

  • Rely on placeholders instead of labels
  • Close </form> before inputs or buttons
  • Trust browser validation alone for security
  • Forget enctype when uploading files
  • Leave optional fields without clear indication

Conclusion

HTML forms are the bridge between users and your application. By wrapping controls correctly, setting action and method, validating input, and reading data with FormData, you can build accessible, reliable data collection on any site.

Next, add images to your pages with the HTML Images tutorial, or review the form tag reference and HTML Inputs guide.

❓ Frequently Asked Questions

A form is a container element that groups interactive controls—inputs, textareas, selects, and buttons. When submitted, the browser collects named field values and sends them to a server or handles them with JavaScript.
On submit, the name becomes the key in the data sent to the server. Fields without a name are ignored. Always set name on controls you want included in the submission.
GET appends form data to the URL as query parameters—fine for searches. POST sends data in the request body—preferred for logins, registrations, and anything sensitive.
It sets how form data is encoded. Use enctype="multipart/form-data" when uploading files. The default application/x-www-form-urlencoded works for most text fields.
No. Browser validation improves user experience but can be bypassed. Always validate and sanitize data again on the server before storing or using it.
Listen for the submit event, call event.preventDefault() to stop navigation, then use new FormData(form) to read values with data.get("fieldName") or iterate all entries.

⚡ Quick Reference

Element / AttributePurpose
<form>Container for controls
actionSubmission URL
methodget or post
enctypeData encoding (files need multipart)
name (on inputs)Key sent with form data
<label for>Accessible field label
requiredMandatory field
FormDataRead values in JavaScript

Key Takeaways

🏷️ 02

label

Always pair.

a11y
📥 03

action

Where sent.

POST
04

validate

Client + server.

Security
⚙️ 05

FormData

JS access.

API

Universal Browser Support

HTML forms work in every browser. HTML5 validation, FormData, and fieldset are supported in all modern browsers. Test file uploads and custom validation messages on mobile Safari and Chrome.

Baseline · Since HTML

HTML forms + FormData

HTML forms work in every browser. HTML5 validation, FormData, and fieldset are supported in all modern browsers. Test file uploads and custom validation messages on mobile Safari and Chrome.

98% Modern browser support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
HTML forms + FormData Modern browsers

Bottom line: Core form elements are universal; HTML5 validation and FormData cover virtually all users today.

Did you know?

Pressing Enter inside a text input submits the form automatically—the browser activates the first submit button. Use type="button" on non-submit buttons to avoid accidental submissions.

Build a contact form in the editor

Add labels, validation, and JavaScript FormData handling, then preview live.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful