Programming

HTML forms

form, input, label, button and field types.

All lessons · HTML lessons: learn from scratch

form, label and input

A <form> collects user data: action is where the data is sent and method is how (get or post). Each field is an <input>, with a <label> for its name; the for attribute links the label to the field's id.

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

Without a name attribute the field's value is not sent. Clicking a label focuses its field, which is very convenient on mobile.

Field types

The type attribute tells the browser what the field is for: text, email, password, number, date, checkbox, radio, file. The right type adapts the mobile keyboard and performs validation. For long text there is <textarea>, for dropdowns <select>.

<input type="number" name="age" min="0" max="120">
<input type="date" name="birthday">
<input type="checkbox" id="agree" name="agree"> <label for="agree">I agree</label>
<select name="city">
  <option value="baku">Baku</option>
  <option value="ganja">Ganja</option>
</select>
<textarea name="message" rows="4"></textarea>

Validation and buttons

  • required demands that the field be filled.
  • minlength, maxlength, min, max and pattern set limits.
  • placeholder is a hint, not a replacement for label.
  • <button type="submit"> sends, type="reset" clears.

Browser validation is for convenience; for security always validate the data on the server as well.

<input type="text" name="user" minlength="3" maxlength="20" required placeholder="Username">
<input type="text" name="zip" pattern="[0-9]{4}" title="4 digits">

Author: Nibras Code