How to Create a Form in HTML: Simple Guide with Examples
<form> element to wrap input fields like <input> and <button>. The form collects user data and can send it to a server when submitted.Syntax
The basic structure of an HTML form uses the <form> tag. Inside it, you add input elements like text boxes, checkboxes, and buttons. The action attribute tells where to send the data, and method defines how to send it (usually GET or POST).
<form>: Container for form elements.action: URL to send form data.method: HTTP method to send data.<input>: Field to enter data.<button>: Button to submit the form.
<form action="/submit" method="post"> <input type="text" name="username" placeholder="Enter your name"> <button type="submit">Submit</button> </form>
Example
This example shows a simple form with a text input for a name and a submit button. When you type your name and click Submit, the form data is sent to the server URL specified in action.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple HTML Form</title> </head> <body> <form action="/submit" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name" placeholder="Your name" required> <button type="submit">Send</button> </form> </body> </html>
Common Pitfalls
Common mistakes when creating forms include forgetting to set the name attribute on inputs, which means data won't be sent. Another is missing the method or action attributes, so the form doesn't know where or how to send data. Also, not using <label> tags can hurt accessibility.
<!-- Wrong: Missing name attribute --> <form action="/submit" method="post"> <input type="text" placeholder="Name"> <button type="submit">Submit</button> </form> <!-- Right: Added name attribute --> <form action="/submit" method="post"> <input type="text" name="username" placeholder="Name"> <button type="submit">Submit</button> </form>
Quick Reference
Here are quick tips to remember when creating HTML forms:
- Always use
<form>to group inputs. - Set
actionto the URL where data goes. - Use
method="post"for sending data securely. - Give each input a
nameattribute for data keys. - Use
<label>for better accessibility. - Use
requiredattribute to make fields mandatory.