HTML forms are used to collect user input on web pages. They allow users to submit data, such as text, numbers, or choices, which can then be processed by a server or client-side script.
Forms are essential for interactive elements like login pages, registration forms, and surveys.
Basic Structure of an HTML Form
An HTML form is defined using the <form>
element. Here’s a simple example:
<form action="/submit" method="post"> <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> <input type="submit" value="Submit"> </form>
Key Attributes of HTML Forms
action
: Specifies the URL where the form data will be sent when the form is submitted. For example,action="/submit"
sends the form data to the/submit
endpoint.method
: Defines the HTTP method used to send the form data. Common methods are:GET
: Appends form data to the URL (suitable for non-sensitive data).POST
: Sends form data in the body of the HTTP request (suitable for sensitive or large data).
name
: Assigns a name to the form, which can be useful for JavaScript or when submitting the form data.target
: Specifies where to open the response after form submission. Values include:_self
(default): Opens in the same frame._blank
: Opens in a new window or tab._parent
: Opens in the parent frame._top
: Opens in the full browser window.
Form Controls and Their Attributes
<input>
: Used for various types of user input. The type
attribute specifies the input type (e.g., text
, password
, submit
, radio
, checkbox
).
<input type="text" name="username" placeholder="Enter your username"> <input type="password" name="password" placeholder="Enter your password">
<textarea>
: Allows for multi-line text input.
<textarea name="message" rows="4" cols="50" placeholder="Enter your message"></textarea>
<select>
: Creates a dropdown list.
<select name="options"> <option value="option1">Option 1</option> <option value="option2">Option 2</option> </select>
<button>
: Defines a clickable button.
<button type="submit">Submit</button>
<fieldset>
: Groups related elements within a form. Often used with <legend>
to provide a caption for the group.
<fieldset> <legend>Personal Information</legend> <label for="name">Name:</label> <input type="text" id="name" name="name"> </fieldset>
<label>
: Associates a text label with a form control using the for
attribute.
<label for="email">Email:</label> <input type="email" id="email" name="email">
These attributes and elements are integral to creating functional and user-friendly forms in HTML.