On this page
Forms and Input Elements
Building Forms (<form>
, <input>
, <textarea>
, <button>
)
Creating a Form (<form>
)
To create a form in HTML, use the <form>
tag. It’s used to collect user input that can be submitted to a server for processing:
<form action="/submit-form" method="post">
<!-- Form fields go here -->
</form>
action
: Specifies the URL where the form data will be submitted.method
: Defines the HTTP method used to send the form data (post or get).
Form Fields
Text Input (<input type="text">
)
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeholder="Enter your username" required>
type="text"
: Creates a single-line text input field.id
,name
: Unique identifier and name for the input field.placeholder
: Placeholder text displayed in the input field before the user enters data.required
: Specifies that the field must be filled out before submitting the form.
Textarea (<textarea>
)
<label for="message">Message:</label>
<textarea id="message" name="message" placeholder="Enter your message" required></textarea>
<textarea>: Creates a multi-line text input field for longer text entries.
Button ()
<button type="submit">Submit</button>
<button>: Creates a clickable button that can submit the form when clicked.
Complete Example
Putting it all together, here’s an example of a complete HTML form with various input fields and a submit button:
<form action="/submit-form" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" placeholder="Enter your username" required><br><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message" placeholder="Enter your message" required></textarea><br><br>
<button type="submit">Submit</button>
</form>
Explanation:
- The
<form>
tag defines the form structure. - Inside
<form>
, various input fields like<input>
and<textarea>
are used to collect user data. - The
<button>
tag creates a submit button to send the form data to the server. - Attributes like action, method, name, id, placeholder, and required are used to define form behavior and validation.
Summary:
- HTML forms (
<form>
,<input>
,<textarea>
,<button>
) are used to collect user input. - Form attributes (
action
,method
,name
,id
,placeholder
,required
) control form behavior and validation. - Using these elements and attributes, you can create interactive forms for user interaction and data submission on webpages.