Introduction
The <form>
element in HTML is used to create an interactive form on a web page. Forms are a crucial part of web development and are used for collecting and submitting user input, such as text, numbers, checkboxes, radio buttons, and more. The <form>
element provides a container for organizing and structuring form controls.
Here’s a basic example of a simple form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/submit_form" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Output :
In this example:
- The
<form>
element contains various form controls such as text inputs and a submit button. - The
action
attribute specifies the URL to which the form data will be sent when submitted. - The
method
attribute defines the HTTP method (e.g.,GET
orPOST
) used for form submission.
Key points about the <form>
element:
- Form Controls: It contains various form controls like text inputs, checkboxes, radio buttons, select boxes, and more, allowing users to input information.
- Action Attribute: Specifies the URL or script that will process the form data when it is submitted. This is typically a server-side script.
- Method Attribute: Defines the HTTP method used for form submission. The two common methods are
GET
(default) andPOST
.GET
is used for requesting data from a specified resource, whilePOST
is used for submitting data to be processed to a specified resource. - Label Elements: It’s good practice to use
<label>
elements associated with form controls using thefor
attribute. This improves accessibility and usability. - Required Attribute: The
required
attribute on form controls indicates that the user must fill in that particular field before submitting the form. - Submit Button: The
<input type="submit">
or<button type="submit">
element is used to create a button that, when clicked, submits the form.
Forms are crucial for various web applications, user authentication, data collection, and more. They facilitate user interaction by allowing users to provide input and interact with the website or application.
Developers often use JavaScript to enhance the interactivity of forms and validate user input on the client side before submitting the data to the server.