HTML Forms

Why is this important?

This workshop is important because:

Forms are an important way a web application receive user input. The proper use of forms makes it easier to develop accessible websites with a good user experience.

What are the objectives?

After this workshop, developers will be able to:

  • describe the basics of the client/server model
  • Evaluate the proper usage of HTML form and input options
  • identify the difference between a method and an action
  • Create forms that generate query parameters

Where should we be now?

Before this workshop, developers should already be able to:

  • Write HTML & JavaScript
  • Understand the basics of the client/server model

What is HTTP?

HTTP stands for hypertext transfer protocol. It is the standard that determines the data format of any information moving between websites. To make an HTTP request, you need three things.

  1. An address where you'll make the request.

  2. An HTTP verb, which will specify the action you request at that address. Here are the possible HTTP verbs:

    • POST - (Create) create an entry in the database we access.
    • GET - (Read) find and return an entry from the database.
    • PUT - (Update/replace) change a specific entry at that address by replacing it with a new entry.
    • PATCH - (Update/modify) change a specific entry at that address by updating it with new data.
    • DELETE - (Delete) remove an entry from the database.
  3. (Optional) Any data that might be necessary in passing along your request.

Client / Server Model

client/server

An Example <form> Element (Tag)

<form method="POST" action="/entries">
  <input type="text" name="title" />
  <input type="text" name="content" />
  <input type="submit" value="Create an Entry" />
</form>

Attributes

By default, when a form is submitted, it generates an HTTP request. In the opening of the <form> tag you can see two attributes: method & action

  • method: the HTTP verb (method) that the browser uses to submit the form.
  • action: the path of the HTTP request page that processes the information submitted via the form. Although it's a bit strange, action specifies where to take action - it's the address for the HTTP request.

A route is simply a combination of a method & action. For example GET '/page' or POST '/users' are both valid routes.

For now simply understand that it is convention for GET to be used in a request when the person using your site (the client) wants to receive data, and for POST to be used in a request when the client wants to send data.

Challenge: Doomed?

Create an HTML form that, on submit, sends the user to "hasthelargehadroncolliderdestroyedtheworldyet.com". This form will only have one input: the submit button. Hint: what's the form action? Bonus: Can you change the submit button to say "Are we doomed?".

Example solution
<form action="http://hasthelargehadroncolliderdestroyedtheworldyet.com" method="GET">
  <input type="submit" value="Are we doomed!?">
</form>

Common Inputs

Field Type HTML Code Widget (Control) Notes
plain text <input type="text"> <input type="text"> the type attribute can be omitted
password field <input type="password"> <input type="password"> echoes dots instead of characters
text area <textarea></textarea> <textarea></textarea> a more customizable plain text area
checkbox <input type="checkbox"> <input type="checkbox"> can be toggled on or off
radio button <input type="radio"> <input type="radio" name="group"> <input type="radio" name="group"> can be grouped with other inputs
drop-down lists <select><option> <select><option>Option 1</option><option>Option 2</option></select> check here for more info
file picker <input type="file"> <input type="file"> pops up an “open file” dialog
hidden field <input type="hidden"> nothing there!
submit button <input type="submit"> <input type="submit"> activates the form's submission
(a POST request or
Javascript action)

Important Attributes

All input types (including <textarea>s) have the following attributes:

  • type: the type of data that is being input (affects the "widget" that is used to display this element by the browser).
  • name: the key used to describe this data in the HTTP request.
  • id: the unique identifier that other HTML elements, JavaScript and CSS use to access this element in the browser.
  • value: the default data that is assigned to the element.
  • placeholder: not a default value, but a useful HTML5 addition of a data "prompt" for an input.
  • autofocus: defaults the cursor to a specific input when the page originally loads. You can only have one autofocus on your page.
  • disabled: a Boolean attribute indicating that the "widget" is not available for interaction.
  • required: a Boolean attribute indicating that the field must have a value / cannot be left empty.

Radio buttons or checkboxes:

  • checked: a Boolean that indicates whether the control is selected by default (is false unless).
  • name: the group to which this element is connected. For radio buttons, only one element per group (or name) can be checked.
  • value: the data or value that is returned for a specific group (a multi-element control), if this element is checked.

You may be thinking to yourself, "An HTTP request has optional data that it should be able to send too. Where does that come from in the form?"

Great question!

The data portion comes from the name and value attributes of the inputs!

Challenge: Login Form

Create an html form with two inputs: one for a username (named "username"), the other for password (named "password") (normally you don't see your password when you type it, so make sure it's blocked out!). What happens in the URL when you click submit?

Example solution
<form>
	<input type="text" name="username" placeholder="cooluser1234" required>
	<input type="password" password="password" placeholder="password" required>
	<input type="submit">
</form>

Form Submission Experiments

1) Given the following HTML...

<form>
    <input name="instrument" value="bongos"> <!-- Text Field -->
    <input type="submit">                   <!-- Submit Button -->
</form>
What endpoint/action are we submitting to?

We did not supply a form action. That means that it will default to the current endpoint. In other words, you will refresh the current page.

What data will be submitted to the server?

instrument: "bongos"

What will that data look like? How will it be formatted?

It will be in the form of a query parameter: ?instrument=bongos

2) Given the following HTML...

<form id="artist-search-form" action="https://musicbrainz.org/search" method="GET">
    <label for="query">Search by Artist</label>
    <input id="query" name="query" value="Adele">
    <input id="type" name="type" value="artist" hidden>
    <input type="submit">
</form>
What endpoint/action are we submitting to?

We are making a GET request to https://musicbrainz.org/search.

What data will be submitted to the server?

query: "Adele", type: "artist"

What will that data look like? How will it be formatted?

?query=adele&type=artist

Form Submission

Sometimes we want to submit a form, in the background, without ever refreshing the page. This is a common pattern in modern "single page applications". How do you submit form data in the background?

When a form is submitted, it triggers the submit event. We can set an event listener on the form using an element's method .addEventListener, or using jQuery's .on. Additionally, in order to stop the form from submitting, we have to prevent its default behavior. Calling preventDefault will allow us to do something other than send the default HTTP request. (We'll see an example of what we might do when we talk about AJAX.)

$("#artist-search-form").on("submit", function(event) {
    event.preventDefault(); // Stops the form from GETting from musicbrainz.org!
    alert("We've submitted the form!")
})

Then we can drill down into the form's data by selecting children elements inside it.

// target the form
$("#artist-search-form").on("submit", function(event) {
  // stop the form from submitting!
  event.preventDefault();
  // grab the user input
  var artist = $("#query").val();
  var type = $("#type").val();
  // do something with the user input
  console.log(artist, "is a", type);
});

Note: jQuery's text method will not work on inputs!

If we want to grab all of the data (name/value pairs) in the form, we can use jQuery's serialize method. We will need to refer to the whole form by using the keyword this, which refers to the element that triggered the event.

$( "#artist-search-form" ).on( "submit", function( event ) {
  event.preventDefault();
  var formData = $(this).serialize();
  console.log(formData); // will console log "query=adele&type=artist" 
});

The <label> element and placeholder attribute

We encourage you to always use the optional <label> tag with each of your form inputs.

"This is the most important element if you want to build accessible forms." — MDN

Label

<label for="password">Password:</label>
<input id="password" type="text" name="password" />

"Do not use the placeholder attribute instead of a label element. Their purposes are different: the attribute describes the role of the form element; that is, it indicates what kind of information is expected, the placeholder attribute is a hint about the format the content should take. There are cases in which the placeholder attribute is never displayed to the user, so the form must be understandable without it." -MDN

Placeholder

<input type="text" name="username" placeholder="cooluser1234">

Make sure the label's for attribute matches the input's id attribute!

Common Validations

Form validations help to prevent users from submitting bad data to the server. They are very important to improve UX, but do not increase the security of the application.

  • a missing or empty field (required)
  • an email address that was missing an "@" symbol (wrong pattern)
  • a password that is obviously too short (invalid length)

required attribute

Try submitting the below form without picking a color:

<form>
  <label for="colorField">What is your favorite color?</label>
  <input id="colorField" name="favColor" required>
  <button>Submit</button>
</form>

Notice the required attribute on the input. Therefore, the form will not submit until some information is entered into the field.

pattern attribute

<form>
  <label for="kindOfBob">Do you go by bob or bobert?</label>
  <input id="kindOfBob" name="bobType" pattern="bob|bobert" required>
  <button>Submit</button>
</form>

The pattern attribute allows us to specify the values we will accept. In this case only bob or bobert are acceptable.

length attribute

You may need the user to enter a specific amount of characters. Let's say you need a username to be at least 6 characters. You can use the minlength or maxlength attributes to help.

<form>
  <label for="password">What's your password?</label>
  <input id="password" type="password" name="password" minlength="8" required>
  <button>Submit</button>
</form>

Independent Practice

Practice with HTML forms in this training.

Closing Thoughts

  • What is a form method and a form action?
  • How do we prevent a form's submission from leaving or refreshing the current page?
  • Do validations make our application more secure?

Additional Resources

MDN has a number of exhaustive resources on HTML forms and inputs. It can be a lot to absorb, so look for patterns and try to grasp the big picture.