HomeHTMLHTML Forms

HTML Forms

Beginner12 min3 views4 of 6

67% through HTML tutorials

HTML Forms

An HTML form is used to collect user input. The user input is most often sent to a server for processing.

The <form> Element

The HTML <form> element is used to create an HTML form for user input:

<form>
  <!-- form elements here -->
</form>

Form Attributes

AttributeDescription
actionURL where data is sent
methodGET or POST
enctypeEncoding type (for file uploads)
autocompleteon/off
novalidateSkip validation

The <input> Element

The <input> element is the most used form element. It can be displayed in many ways depending on the type attribute:

<form action="/submit" method="post">
  <!-- Text input -->
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" placeholder="Enter name" required>
  
  <!-- Email -->
  <label for="email">Email:</label>
  <input type="email" id="email" name="email">
  
  <!-- Password -->
  <label for="pwd">Password:</label>
  <input type="password" id="pwd" name="pwd" minlength="8">
  
  <!-- Number -->
  <label for="age">Age:</label>
  <input type="number" id="age" name="age" min="1" max="120">
  
  <!-- Date -->
  <input type="date" name="birthday">
  
  <!-- Checkbox -->
  <input type="checkbox" id="agree" name="agree">
  <label for="agree">I agree to terms</label>
  
  <!-- Radio buttons -->
  <input type="radio" id="male" name="gender" value="male">
  <label for="male">Male</label>
  <input type="radio" id="female" name="gender" value="female">
  <label for="female">Female</label>
  
  <!-- Submit -->
  <input type="submit" value="Submit">
</form>

Select Dropdown

<label for="lang">Choose a language:</label>
<select id="lang" name="language">
  <option value="">-- Select --</option>
  <option value="html">HTML</option>
  <option value="css">CSS</option>
  <option value="js" selected>JavaScript</option>
</select>

Textarea

<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="50"
  placeholder="Type your message..."></textarea>

HTML5 Form Validation

HTML5 added built-in form validation:

<input type="email" required>           <!-- Must be filled -->
<input type="text" minlength="3">       <!-- Min 3 characters -->
<input type="number" min="0" max="100"> <!-- Number range -->
<input type="text" pattern="[A-Z]{3}"> <!-- Regex pattern -->

Test Your Knowledge

2 questions · Pass with 70%+

1What attribute makes a form field required?

2Which input type is used for email addresses?

0 / 2 answered