Dr. Greg Bernstein
Updated March 21st, 2021
Your first form. Basics of the <form>
element, action, and submit button.
How to structure a form. How to use fieldsets, legends, labels, and such.
In the beginning the <form>
element was the only way for browsers to send data to servers, then came file upload, and after that AJAX.
<form>
The essential format of a for element:
<form action="url" method="post">
<!-- Form contents -->
<!-- Need at least one submit button -->
<button type="submit">Your Button text</button>
</form>
<form>
attributesaction: The URL (absolute or relative) of the page that will handle this form, i.e., where it will be submitted.
method: The HTTP method used by the form. Either “get” or “post”.
For <input>
s the following attributes are used:
name: This is submitted with the form to identify which of multiple inputs the value represents.
value: Submitted along with the form with its associated name.
id: Not submitted with the form
From MDN:
<form action="/my-handling-form-page" method="post">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="user_name">
</div>
<div>
<label for="mail">E-mail:</label>
<input type="email" id="mail" name="user_mail">
</div>
<div>
<label for="msg">Message:</label>
<textarea id="msg" name="user_message"></textarea>
</div>
<button type="submit">Send your message</button>
</form>
get
and post
BehaviorWhere form data is put in the HTTP message depends on the method
attribute
get
methods encode form data as part of the URL
post
methods encode form data as part of the HTTP request mesage body. This is common when using forms that actually post data to a server.Commonly uses Content-Type: application/x-www-form-urlencoded
From MDN
POST / HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13
say=Hi&to=Mom
The node-fetch library for Node.js has support for form submission “emulation”
With Express.js we will need some middleware to help us parse form bodies (post requests). We’ll use express.urlencoded.
<fieldset>
can be used to group a bunch of form elements<legend>
can be used to a “label” to the field set<fieldset>
<legend>A similar set of things</legend>
<button>One</button>
<button>Two</button>
<button>Three</button>
</fieldset>