12. HTML Forms
What you will learn
- What a form is and how it sends data
- How to add inputs and labels
- The
action,method, andnameattributes - Why a form needs server-side code
What is a form?
A form collects information from visitors, such as a name, an email address, or a message. The <form> element wraps all the form controls.
A first form
Example
<form action="/subscribe" method="post">
<label for="email">Email address</label>
<input type="email" id="email" name="email">
<button type="submit">Subscribe</button>
</form>
Output (a display-only demo that does not send anything)
The code, step by step
<form>wraps the controls.actionis the address that receives the data.methodis how it is sent.<label>describes a field. Itsforvalue matches the input’sid, so clicking the label focuses the field.<input>is the field.type="email"asks the browser to expect an email address.nameis the label attached to the data when it is sent. A field without anameis not sent.<button type="submit">sends the form.
GET and POST
- GET puts the data in the web address. Use it for searches, where the result can be bookmarked.
- POST sends the data in the body of the request. Use it for logins, messages, and anything private or that changes something.
Text area and drop-down list
Example
<label for="topic">Topic</label>
<select id="topic" name="topic">
<option value="html">HTML</option>
<option value="css">CSS</option>
</select>
<label for="msg">Message</label>
<textarea id="msg" name="msg" rows="4" cols="30"></textarea>
Output
Built-in validation
The required attribute stops the form from being sent if the field is empty. The browser shows a message.
Example
<input type="text" name="username" required>
Security: browser checks help visitors but can be bypassed. A real website must always check the data again on the server. A form also does nothing until server code (for example PHP) receives it. You will learn this in the PHP course.
Common mistakes
- Leaving out
name, so the value is never sent. - Skipping
<label>and using only placeholder text. Placeholders disappear when typing and are not a replacement for labels. - A
forthat does not match anyid. - Using GET for passwords.
Exercise
Write a form that sends by POST to /contact with a labelled text field named fullname and a submit button called Send.
Show solution
<form action="/contact" method="post">
<label for="fullname">Full name</label>
<input type="text" id="fullname" name="fullname">
<button type="submit">Send</button>
</form>
Knowledge check
1. Which attribute decides where form data is sent?
action
2. Which attribute links a label to an input?
for on the label, matching the input’s id.
3. Which method is better for a login form?
POST.
Summary
<form>wraps controls and usesactionandmethod.- Every field needs a
nameand a visible<label>. - Browser validation helps, but the server must validate too.