🌱BeginnerForms
Form Basics
Create HTML forms with the <form> element, understand action and method attributes.
Overview
HTML forms are how users submit data to a web server login pages, search boxes, contact forms, checkout flows, and signup pages are all built on the <form> element.
The <form> element is a container for input controls. Two key attributes control what happens when the form is submitted:
- action: the URL to send the data to (defaults to the current page)
- method: how to send the data GET (appended to URL) or POST (in the request body)
Within the form you add input elements (<input>, <textarea>, <select>), a submit button, and labels. Modern browsers also provide built-in validation.
Key Points
- •<form action="/submit" method="POST"> is the basic form container syntax
- •method="GET" appends form data to the URL: ?name=John&age=30 visible, bookmark-able
- •method="POST" sends data in the request body better for sensitive data and large payloads
- •action defaults to the current URL if omitted
- •Every input needs a name attribute to be included in the submitted data
- •A submit button (<button type="submit"> or <input type="submit">) sends the form
Examples
A minimal search form using GET
<form action="/search" method="GET">
<input type="text" name="q" placeholder="Search...">
<button type="submit">Search</button>
</form>GET forms appear in the URL as /search?q=query great for searchable, shareable URLs.
A contact form using POST
<form action="/contact" method="POST">
<input type="text" name="name" placeholder="Your name">
<input type="email" name="email" placeholder="Your email">
<textarea name="message" placeholder="Your message"></textarea>
<button type="submit">Send</button>
</form>POST sends data in the request body use it for login, signup, and contact forms.
Preventing default submission for JavaScript handling
<form id="myForm">
<input type="text" name="username">
<button type="submit">Login</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', (e) => {
e.preventDefault(); // Stop default submit
// Handle with JavaScript / fetch
});
</script>Common Mistakes
- Using GET for login forms passwords appear in the URL and browser history
- Forgetting name attributes on inputs nameless fields are not submitted
- Using type="button" on the submit button when you want type="submit"
Note
Use GET for searches and filters (users can bookmark the results), and POST for anything that creates or modifies data on the server (logins, sign-ups, orders).
Exercises
Write HTML to solve each exercise. Use Preview to see it render in a live iframe, then mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4