HTML/CSS - 12
HTML/CSS - 12: Forms & User Input
Forms let visitors enter information into a webpage. They can be used for things like contact forms, sign-up pages, surveys, and search boxes.
A basic form is built with a <form> element. Inside it, you can place <label> elements to describe each field, <input> elements for short answers, a <textarea> for longer messages, and a <button> to submit the form.
Labels are important because they tell the visitor what each field is for. A label can connect to an input using matching for and id values.
Your challenge: Build a simple contact form with a name field, email field, password field, message box, and submit button.
What should you notice?
Each form field has a different job. A text input is useful for short answers, an email input is designed for email addresses, and a password input hides the characters being typed.
The <textarea> element is useful when the visitor may need to write more than one short line, such as a message or comment.
Labels and inputs: A label can be connected to a field by matching its for value with the input's id.
For example: <label for="name">Name</label> and <input type="text" id="name"> belong together because both use the word name.
Experiment: Click directly on one of your labels. If the for and id values match, the related input should receive focus.
Try validation: Add the required attribute to one or more fields, then press the submit button without filling them in. The browser should stop the form from submitting and ask for the missing information.
Good HTML habit: Use the input type that matches the information you expect. For example, use type="email" for an email address rather than using type="text" for everything.
Important: This lesson creates the visible form and demonstrates browser validation. It does not send the information anywhere yet. A real form also needs a destination or some JavaScript/server-side code to process the submitted data.
👀 Show Solution
<form>
<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="password">Password</label>
<input
type="password"
id="password"
name="password"
required>
<label for="message">Message</label>
<textarea
id="message"
name="message"
required></textarea>
<button type="submit">Send Message</button>
</form>Each field has a label, a matching id, and a name. The required attribute tells the browser that the field must be completed before submission.
The email field also uses type="email", so the browser can check whether the entered value looks like an email address.
