---
# System prepended metadata

title: COMP 1850 Lesson Ten
tags: [COMP-1850]

---

---
tags: COMP-1850
---
<style>
    .markdown-body h1:first-of-type {
        margin-top: 24px;
    }
    .markdown-body h1 {
        margin-top: 64px;
    }
    .markdown-body h1 + h2 {
        margin-top: 32px;
    }
    .markdown-body h2 {
        margin-top: 48px;
    }
    .markdown-body h3 {
        color: cornflowerblue;
    }
    .exercise {
        font-size: 150%;
        font-weight: bold;
        color: rgb(227,112,183);
    }
    .note {
        color: red;
    }
</style>


## HTML Forms

Much of the important interaction between users and websites occurs via ==forms==, sets of ==fields== that allow users to _send_ data to a server. Examples of common actions that require forms are:

- Logging into a website
- Searching for (and within) websites
- Adding products to a cart
- Signing up to a mailing list
- Transferring money between online bank accounts

HTML forms at their simplest are a parent `form` tag with several required attributes (discussed below), and child elements (fields) that capture various kinds of data from a user.

Below is an example of a simple login form with two fields: a username, password; and a button for submitting (sending) the data:

```
<form>
    <input type="text" name="email">
    <input type="text" name="password">
    <input type="submit" value="Submit">
</form>
```

The `input` element in the example above is one of the HTML element types that can be used for form fields, and typically has a minimum of two attributes: `type` and `name`. `type` determines the kind of data the field expects (plain text? email? password? number?) and `name` associates a name with the data that a user sends, so that the receiving page or script can understand it. Here's a simple example:

_Chris fills out the form above, entering 'charris17@bcit.ca'  into the first field, and 'pa55word' into second field, then clicks the submit button._

_The server receives the data as key/value pairs, `email:charris17@bcit.ca` and `password:pa55word`._

Copy this HTML into a page and you will see two text inputs and a button, but clicking the button will simply refresh the page and erase any value you may have typed in to the email or password fields. 

Why does the page refresh and erase our data? Because we have not yet specified _where_ the data should go and _how_ it should get there.

### The `action` and `method` attributes 
    
The `action` attribute on the `form` element is akin to `href` on a link – it tells the browser _where_ to send the data the user types in. The URL value that we provide for the `action` attribute could be another HTML page, or a URL without an HTML page that is capable (via a backend scripting language for example) of taking the user data and doing something with it - in this case possibly checking to see if the password and email address are correct.

The `method` attribute tells the browser _how_ to send the data. Though there are many methods available, this course will focus on two: `GET` and `POST`.

Below is the same example as above with the addition of attributes on the `form` tag:

```
<form method="GET" action="/receive.html">
    <input type="text" name="email">
    <input type="text" name="password">
    <input type="submit" value="Submit">
</form>
```

`GET` takes each piece of data and appends the key/value pairs to the end of the URL specified in the `action` attribute, so assuming the data is sent as noted above (`email:charris17@bcit.ca, password:pa55word`), the form would be sent to `/receive.html?email=charris17@bcit.ca&password=pa55word`

Note how a `?` is added to the end of the URL before the data, and each key/value pair is separated by an ampersand `&`.

Try this in the browser and you will see the URL noted above in your address bar.

The previous example successfully sends data, but there are several issues that should be mentioned:

1. The URL becomes part of the browser history, so if the browser was used on a shared public computer an attacker could read the login information
2. The request could potentially be sent as plain, unencrypted text, so an attacker able to see network traffic would also have access to the login information via the URL
3. GET requests have a limit to how long the data can be

All of the above issues can be remedied by using the `POST` method instead.

The `POST` method sends the key/value pair data as part of the [HTTP Header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers), meaning that the data is not appended to the URL and does not suffer from the same length limits as `GET`. For that reason, in any case where you expect to receive sensitive data from a user (e.g. username and password) you should use the `POST` method.

### HTML form elements

HTML provides a wide variety of elements to capture data from users. The `input` element mentioned above is the most common, and has many _types_ designed to help validate data and aid users. Below are the most commonly used types:

- text
- email
- password
- tel (phone number)
- url
- number
- range (slider for numeric values)
- datetime-local
- color (color picker)
- file (for uploading files)
- radio
- checkbox
- submit

Other commonly used fields that are not `input` elements are:

- select (used with the 'option' element to create dropdowns)
- textarea (for multiline text)

Below is an example of a form with several input types, a select, and textarea:

```
<form method="GET" action="/receive.html">
    <p>
        <label for="user_email">Email:</label>
        <input type="email" name="user_email" id="user_email">
    </p>
    <p>
        <label for="user_password">Password:</label>
        <input type="password" name="user_password" id="user_password">
    </p>
    <p>
        <label for="user_phone">Phone:</label>
        <input type="tel" name="user_phone" id="user_phone">
    </p>
    <p>
        <label for="user_course">Select a course:</label>
        <select name="user_course" id="user_course">
            <option value="comp1850">COMP 1850</option>
            <option value="comp2132">COMP 2132</option>
        </select>
    </p>
    <p>
        <label for="user_comments">Comments:</label>
        <textarea name="user_comments" id="user_comments">
    </p>
</form>
```

Two new things to note about the above example: first, for accessibility, a `label` element has been added for each form field. This label element will be read aloud by screen readers, and makes the fields easier to click for users who have motor disabilities.

Second, the `value` attribute on each `option` element is the data that will be sent for the `user_course` field; the text in between the opening and closing `option` tags is what is shown to the user.

## Form Validation

Many of the types of `input` elements mentioned above provide built-in validation and functionality: an email field will prevent a form from being submitted until a value resembling a valid email address is entered by the user, and the `password` element hides the characters that are typed into the field.

For other types of validation, HTML5 provides several attributes that can be added to a form field:

- min (minimum allowed value for numeric fields)
- max (maximum allowed value for numeric fields)
- minlength (minimum allowed length for text fields)
- maxlength (maximum allowed length for text fields)
- required (the form cannot be submitted until a value is present)
- pattern (specifies a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions) that the value must match)

Note that the `type` attribute is also a form of input validation.

Below is an example of a simple form with the following properties:

1. The username is required and must be at least 8 characters
2. The password is required, must be at least 16 characters, and must begin with at least one uppercase character

```
<form method="GET" action="/receive.html">
    <p>
        <label for="user_email">Email:</label>
        <input type="email" name="user_email" id="user_email">
    </p>
    <p>
        <label for="user_password">Password:</label>
        <input type="password" required minlength="16" pattern="[A-Z]+.*" name="user_password" id="user_password">
    </p>
    <p><input type="submit" value="Submit"></p>
</form>
```

---

<span class="exercise" id="a5c">Assignment 6: HTML Forms and CSS Grid</span>

For assignment 6 you will be acquiring some free hosting and publishing a page using HTML Forms and CSS Grid.

## Part 1

Begin by signing up for a Netlify account:

 1. Enter your email address and password of choice at https://app.netlify.com/signup/email. 
 2. Verify your email address by clicking the link in the email you receive.
 3. Answer (or skip) the questions regarding how you intend to use Netlify, taking you to a page with the heading 'Deploy your first project'
 4. Click the 'Try Netlify Drop' link toward the bottom of the page, taking you to https://app.netlify.com/drop 
 5. At this point you may leave the browser temporarily to prepare some files:
    a. Create a folder on your hard drive, named whatever you like
    b. Create two files inside the folder, named index.html and index.css 
    c. Populate the index.html and index.css files with some starter content (e.g. a basic page with head, body, and an h1)
6. Once your folder and files from step 5 are ready, drag them from the File Explorer into the Netlify window in your browser - if successful you should be navigated to a new page on the Netlify site with a popup saying 'Deploy success!'. Click 'Get started'

You should now be on the homepage of your Netlify account. This page contains a lot of information, but most importantly a link to the main page for your new site - look for a heading towards the bottom of your homepage with the heading 'Sites'. 

Underneath the Sites heading you should see a link to the configuration page of your new site, which will have been assigned a random domain name, e.g. 'willowy-cranachan-65c989' and have the phrase 'Manual deploys' underneath it. Click this link to go to your configuration page.

Your configuration page will show at the top your URL, e.g. https://willowy-cranachan-65c989.netlify.app. Copy and paste this URL into a new tab in the browser to view your already published site.

You now have live hosting for your HTML, CSS and JS website! Later we will discuss how to purchase and change the domain (from your randomly generated URL to one of your own choice) but for the time being you can start to work on your page(s) and publish the changes to Netlify.

Once you have added the content described below, you can re-deploy the site by going back to the configuration page for your site in Netlify and clicking 'Deploys' from the menu on the left-hand side of the page. This page provides an interface where you can drag and drop the updated files from your computer to Netlify.

## Part 2

For this assignment your finished page on Netlify must contain an HTML form that will serve as a way for a potential client to book a consultation with you (for web, design, or SEO services).

Your booking form must have the following fields:
- a text input with label "Full Name"
- an email input with label "Email Address"
- a phone input with label "Phone Number"
- a dropdown with the following options:
    - Website
    - Design
    - SEO
- a date picker
- a number input with label "Consultation Length (hours)"
    
The booking form must also include the following form validation:
- every form control except Phone Number must be required
- use the pattern attribute to ensure that the email address ends in .com and contains the @ symbol
- use the pattern attribute to ensure that the phone number is in the following format:
    (604)-234-4567   i.e. three-digit area code in parentheses, and dashes between each portion of the number
- ensure that the Consultation Length field only accepts values between 1 and 4 inclusive (i.e. consultations must be minimum one hour long, maximum 4 hours long)

In addition, the form must be styled using CSS grid such that the left-hand side of all fields and labels must be aligned (i.e. labels in one column, fields in another column) on desktop. On mobile devices (less than 1000px wide) the labels must be above the fields and the fields themselves must take up the full width of the screen (minus any margins on the left and right-hand sides).

Before deploying, read and complete the steps listed here: https://docs.netlify.com/forms/setup/ to enable you to view the submissions made through your form, and verify that information you are sending through the form is being saved correctly.

Once your booking form is complete, deploy it to your Netlify site and submit a .txt file to the Learning Hub that contains a direct link to page.


## Optional Reading Before Next Class

- [Introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Introduction) 


## Tasks To Complete Before Next Class

- [ ] (Optionally) complete the [readings](#Optional-Reading-Before-Next-Class)

---
