# Introduction to forms

  • Forms collect user input for processing on the server.
  • Examples of their use are in a search bar, in user registration, in online surveys, and in e-commerce checkout.
Tag Description
<form> HTML form for user input
<input> Element that accepts input from user
<label> Defines a label for form elements
<textarea> Defines a multi-line input field
<select> Defines a (drop-down) list
<optgroup> Defines a group of related options in a (drop-down) list
<option> Defines an option in a (drop-down) list
<fieldset> Groups related elements in a form
<legend> Defines a caption for a fieldset element
<button> Defines a clickable button

# <form> tag

# Action Attribute

  • The 'action' attribute defines where the form data is sent.
  • It usually contains the URL of a server-side script (like PHP, Python, or Node.js) to process the form data.
  • If the action attribute is omitted, the form data is sent to the current page.

<form action="https://it-fact.be/form.php">
    <!-- Form fields go here -->
</form>
Copied!
1
2
3
4

# Method Attribute

  • The method attribute specifies the HTTP method used to send the form data.
  • The two most common methods are GET and POST.

<form action="https://it-fact.be/form.php" method="post">
    <!-- Form fields go here -->
</form>
Copied!
1
2
3
4

GET VS POST REQUEST

  • GET is typically used when you want to retrieve data. Imagine a search bar in a webshop. When you type in the product name and hit search, your browser sends a GET request to the server to fetch the relevant data. This request doesn't change anything on the server; it only retrieves information. The form data is visible in the URL.
  • POST is used when you want to send data to the server. Consider a registration form on a website. When you enter your information and hit the submit button, your browser sends a POST request to the server with the data you provided. This request can potentially change the state on the server - for example, a new user record will be created in the database. The form data is not visible in the URL.

In summary, use GET when you need to fetch data and POST when you need to send data.

# HTTP Requests

When a form is submitted, it sends an HTTP request to the server. The method used in the request determines the type of action the server should perform. Here are the two most commonly used methods:

  • GET:
    Used to retrieve data from the server, for example: Searching for a product in a webshop.
    • The form data is sent as part of the URL (e.g., ?search=product).
    • It is visible in the browser's address bar.
    • Best for actions that do not change data on the server.
  • POST:
    Used to send data to the server, for example: Submitting a registration form.
    • The form data is sent in the body of the request (not visible in the URL).
    • Best for actions that create or update data on the server.
<!-- Example of GET and POST methods -->
<form action="https://it-fact.be/form.php" method="get">
    <input type="text" name="search" placeholder="Search...">
    <button type="submit">Search</button>
</form>

<form action="https://it-fact.be/form.php" method="post">
    <input type="text" name="username" placeholder="Enter your name">
    <button type="submit">Submit</button>
</form>
Copied!
1
2
3
4
5
6
7
8
9
10

In addition to GET and POST, there are other HTTP methods that are used for specific actions. These will be covered in more detail later in the course:

  • PUT: Used to replace existing data on the server.
  • PATCH: Used to update part of the data on the server.
  • DELETE: Used to delete data from the server.

For now, focus on understanding GET and POST, as they are the most commonly used methods in forms.

NOTE

HTML forms only support the GET and POST methods.
PUT, PATCH, and DELETE requests can be made using JavaScript or other programming languages.

# <label> tag

The <label> tag plays a crucial role in forms as it links form controls with their respective labels. It provides the following benefits:

  • Labels make it easier for users to understand the purpose of a form control.
  • Labels are essential for users who rely on assistive technologies such as screen readers.
  • Clickability: Associating labels with form controls allows users to click on the label text, activating the associated control.

To associate a label with a form control, you can use the for attribute on the label tag and specify the id attribute of the corresponding form control element.

<label for="name">Name:</label>
<input type="text" id="name" name="myName">
Copied!
1
2

Accessibility Best Practices

When designing forms, it is crucial to consider accessibility to ensure that all users, including those with disabilities, can access and use the forms effectively. Here are some best practices to follow:

  • Provide meaningful and descriptive labels
  • Ensure proper form control focus
  • Provide clear error messages and validation

# Form elements

# <input> tags

  • Form data can be collected from input tags.
  • They can have different 'types' like 'text', 'checkbox', 'radio', 'password', etc.

<form action="https://it-fact.be/form.php" method="post">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username">
    <label for="password">Password:</label>
    <input type="password" name="password" id="password">
    <input type="submit" value="Submit">
</form>
Copied!
1
2
3
4
5
6
7
8
  • The type attribute determines the kind of input.
  • The name attribute defines the variable name for the form data.
  • The id attribute is used to associate the input with a label.
  • The value attribute sets the initial value or label of the input field.

# HTML Input Types

Type Description
text (opens new window) A single-line text field.
password (opens new window) A single-line text field where characters are masked (usually shown as asterisks).
search (opens new window) A single-line text field for searching.
url (opens new window) A single-line text field for entering a URL.
email (opens new window) A single-line text field for entering an email address.
hidden (opens new window) An invisible input field that can be used to store form data.
button (opens new window) A push button that can be clicked to trigger an action.
submit (opens new window) A button that submits the form.
reset (opens new window) A button that resets the form to its default state.
file (opens new window) A file upload field.
checkbox (opens new window) A checkbox that can be checked or unchecked to select or deselect an option.
radio (opens new window) A radio button that can be selected to choose one option from a group of options.
image (opens new window) An image submit button.
color (opens new window) A color picker field.
date (opens new window) A date picker field.
datetime-local (opens new window) A date and time picker field that includes both the date and time (with no time zone).
month (opens new window) A month picker field.
number (opens new window) A field for entering a numeric value.
range (opens new window) A slider for selecting a numeric value within a specified range.
tel (opens new window) A field for entering a telephone number.
time (opens new window) A time picker field.
week (opens new window) A week picker field.
file (opens new window) A file upload field.

NOTE

Most input types are just variations of a single-line text input type. Only radio buttons and checkboxes need a bit more explanation.

# Radio Buttons

  • Radio buttons are used when you want the user to select only one option from a set.
  • Grouping radio buttons with the same name ensures that selecting one will unselect any other selected option in the group.
  • The unique id makes sure the input can be linked to a label.

In the example below, both radio buttons have the same name driving_license, which means the user can only select one of the options.

# Checkboxes

  • Checkboxes allow users to select multiple options.
  • Each checkbox needs a unique name to handle the input data and id for specific labeling.

# <textarea> tag

  • The textarea tag is used for multi-line text input.
  • It is useful for collecting longer text inputs like comments, reviews, or longer messages.
  • With the optional rows and cols attributes, you can define the visible number of lines and width of the textarea.

# <select> tag

  • The select tag creates a drop-down list.
  • It is used when the user needs to select one or more options from a list of choices.
  • The optional size attribute can be used to define the number of visible options in the list.

# <option> tag

  • The option tag inside a select tag defines an option in the drop-down list.
  • The text inside the option tag is the visible option, and the value attribute is the value sent to the server when the form is submitted.
  • With the optional selected attribute, you can pre-select an option when the page loads.

# <optgroup> tag

  • The optgroup tag groups related options in a drop-down list. I
  • If you have a long list of options, grouping them can make it easier for users to find the option they need.
  • The label attribute specifies the name of the group of options.

# <button> tag

  • The button tag defines a clickable button.
  • The type attribute specifies the button's behavior. Here are the three common types:
Type Description
submit The button submits the form data to the server (this is the default if the attribute is not specified).
reset The button resets all the form fields to their initial values.
button A clickable button that can be used to attach JavaScript behaviors without submitting the form.
<!-- Example of different button types -->
<button type="submit">Submit</button>
<button type="reset">Reset</button>
<button type="button" onclick="alert('Button clicked')">Click Me</button>
Copied!
1
2
3
4

NOTE

Buttons are also available as input tags with the type attribute set to submit, reset, or button.

  • <input type="submit" value="Submit"> is equivalent to <button type="submit">Submit</button>.
  • <input type="reset" value="Reset"> is equivalent to <button type="reset">Reset</button>.
  • <input type="button" value="Click Me"> is equivalent to <button type="button">Click Me</button>.

Key difference:

Feature <input type="..." value="xyz"> <button>
Content Limited to a value attribute for the button text. Can contain any HTML content (e.g., text, icons, or images).
Styling Styling is limited to the button itself. Can be styled more flexibly, including nested elements.
Use Case Best for simple forms where only text is needed on the button. Best for complex buttons with custom content or additional functionality.

# <fieldset> and <legend> tags

  • The fieldset tag groups related tags in a form.
  • The legend tag defines a caption for the fieldset.

# Validation Attributes

HTML5 validation attributes allow you to validate form data directly in the browser, without the need for JavaScript.
These attributes can make your forms more user-friendly and improve the user experience by preventing incorrect submissions.

# Common Validation Attributes

Attribute Description Example
required Specifies that an input field must be filled out before the form can be submitted. <input type="text" required>
minlength Defines the minimum number of characters allowed in an input field. <input type="text" minlength="5">
maxlength Defines the maximum number of characters allowed in an input field. <input type="text" maxlength="10">
min Specifies the minimum value for numeric or date input fields. <input type="number" min="1">
max Specifies the maximum value for numeric or date input fields. <input type="number" max="100">
step Defines the interval between allowed numbers in an input field. <input type="number" step="5">
pattern Specifies a regular expression that the input's value must match. <input type="text" pattern="[A-Za-z]{3}">
type="email" Validates if the input is a valid email. <input type="email">
type="url" Validates if the input is a valid URL. <input type="url">

NOTE

The pattern attribute uses regular expressions to define the allowed input format. For example, the pattern [A-Za-z]{3} specifies that the input must contain three alphabetic characters. Use a tool like RegExr (opens new window) to test and build your regular expressions.

# Placeholder Attribute

While not a validation attribute, the placeholder attribute can be used to provide a hint or example of the expected input format. It is displayed in the input field until the user starts typing.

# Example

In this example:

  • The username field is required, with a minimum length of 3 characters and a maximum length of 20 characters.
  • The email field is required and is validated to ensure it's a valid email format.
  • The age field is validated to ensure the value is a number between 18 and 99, but it's not required (can be left empty).
  • The postal code field is validated to ensure it matches a format of 4 digits, but it's not required.

IMPORTANT

While client-side validation can improve the user experience, it is essential to remember that it is not a substitute for server-side validation. Server-side validation is crucial for security and data integrity, as client-side validation can be bypassed by users.

Last Updated: 12/30/2024, 2:37:54 PM