Skip to main content

HTML Forms & User Input

Forms are how we "talk" back to a website. Every time you type a search query, log into Facebook, or fill out a contact form, you are using HTML Forms.

1. The Form Container (<form>)โ€‹

All input elements must stay inside a <form> tag. This tag acts as a wrapper that tells the browser where to send the data when the "Submit" button is clicked.

<form action="/submit-data" method="POST">
...
</form>
  • action: The URL (destination) where the data should be sent.
  • method: How the data is sent (usually GET for searching or POST for sensitive data like passwords).

2. The Anatomy of an Inputโ€‹

The <input> tag is unique because its behavior changes completely based on its type attribute.

The Label Tag (<label>)โ€‹

Crucial Rule: Never use an input without a <label>. Labels make your forms accessible to screen readers and allow users to click the text to focus on the input.

<label for="username">Username:</label>
<input type="text" id="username" name="user_login">
  • Note: The for attribute in the label must match the id of the input.

3. Common Input Typesโ€‹

<input type="text" placeholder="Enter Name">

<input type="password" placeholder="Enter Password">

4. The Submit Buttonโ€‹

A form isn't complete without a way to send it. We use the <button> tag or an <input type="submit">.

<button type="submit">Send Message ๐Ÿš€</button>

Putting it All Together: A Registration Formโ€‹

Copy this into your index.html to see a real-world example:

<h2>Join CodeHarborHub</h2>
<form>
<div>
<label for="fname">Full Name:</label><br>
<input type="text" id="fname" required>
</div>

<br>

<div>
<label for="email">Email Address:</label><br>
<input type="email" id="email" required>
</div>

<br>

<div>
<label>Level of Experience:</label><br>
<input type="radio" name="lvl" id="beg"> <label for="beg">Beginner</label>
<input type="radio" name="lvl" id="pro"> <label for="pro">Pro</label>
</div>

<br>

<button type="submit">Create Account</button>
</form>
Validation

Did you notice the required attribute in the code above? This is called HTML5 Validation. It tells the browser not to let the user submit the form if the field is emptyโ€”all without needing any JavaScript!