HTML forms are an important part of web development. They allow users to input data on a web page, which can then be sent to a server for processing. In this tutorial, we will cover the basics of HTML forms, including form elements like input
, select
, and textarea
, as well as form attributes like action
and method
.
Form Elements
There are several different types of form elements that can be used in HTML:
Input
The input
element is used to create a variety of form controls, including text fields, checkboxes, radio buttons, and more. The type
attribute determines what kind of input control is created. For example, the following code creates a text field:
<input type="text" name="username">
The name
attribute is used to identify the input when the form is submitted.
Select
The select
element is used to create drop-down lists. Each option
element within the select
element represents a choice in the list. For example:
<select name="color">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
The value
attribute specifies the value that will be sent to the server when the form is submitted.
Textarea
The textarea
element is used to create a multi-line text input field. For example:
<textarea name="comments" rows="4" cols="40"></textarea>
The rows
and cols
attributes specify the size of the text input field.
Form Attributes
There are several different form attributes that can be used in HTML:
Action
The action
attribute specifies where the form data should be sent when the form is submitted. For example:
<form action="/submit-form.php">
...
</form>
The action
attribute should be set to the URL of the server-side script that will process the form data.
Method
The method
attribute specifies how the form data should be sent to the server. The two most common values for this attribute are GET
and POST
. For example:
<form action="/submit-form.php" method="post">
...
</form>
The method
attribute should be set to GET
if the form data should be sent as URL parameters, or POST
if the form data should be sent in the request body.
Conclusion
HTML forms are a powerful tool for collecting user input on a web page. By using form elements like input
, select
, and textarea
, as well as form attributes like action
and method
, you can create forms that are easy to use and provide valuable data to your web application.