Post

HTML Forms

HTML Forms

Forms are a critical part of a website, and are the user’s gateway into the backend - user provides data in a form for backend to use.

  • Need to specify proper types of inputs for each possible data item.
  • Explore basics of HTML forms and different types of inputs.

HTML Form Element

The form element is a container element like the div element. It wraps all of the inputs a user will interact with on a form.

Two essential attributes accepted:

  • action attribute which takes URL value on where to send data
  • method attribute which tells browser which HTTP request method to use to submit form (e.g. GET, POST requests)
    • GET used to retrieve something from a server
    • POST used to change something on the server.
1
2
3
<form action="example.com/path" method="post">

</form>

Form Controls

Use form control elements to collect user data. These are elements users will interact with on the form, (e.g. text boxes, dropdowns, checkboxes and buttons.)

  • Input Element:
    • It accepts a type attribute which tells the browser what type of data it should expect and how it should render the input element.
    • Accepts any text input.
  • Labels:
    • Used to give inputs a label to inform users what type of entered data is expected.
    • Labels accept a for attribute, which associates it with a particular input. The input we want to associate with a label needs an id attribute with the same value as the label’s for attribute.
    • When associated with an input and clicked, it will focus cursor on the input, ready for user to input some data.
  • Placeholder Attribute:
    • To guide users on what to enter in form elements, we can include placeholder text in input fields.
  • The name Attribute:
    • The name attribute serves as a reference to the data inputted into a form control after submitting it.
    • “variable name” for the input. Form input should always have a name attribute; otherwise, it will be ignored when the form is submitted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!-- Submitting form on httpbin -->
<form action="https://httpbin.org/post" method="post">
  <div>
    <label for="first_name">First Name:</label>
    <input type="text" name="first_name" id="first_name">
  </div>

  <div>
    <label for="last_name">Last Name:</label>
    <input type="text" name="last_name" id="last_name">
  </div>

  <div>
    <label for="age">Age:</label>
    <input type="number" name="age" id="age">
  </div>

  <button type="submit">Submit</button>
</form>

Output from the response is the “form” object.

1
2
3
4
5
"form": {
    "age": "33",
    "first_name": "John",
    "last_name": "Doe"
  }
  • You can use any of the form controls HTML provides outside of the <form> element, e.g. to display somewhere else on the page with JS.

  • The type Attribute:
    • Different input types, e.g. email, password, number, date inputs
    • email inputs are specialized text inputs, includes the @ symbol and validates correctly formatted email addresses. Similarly, password inputs are masked, and number inputs accept only number values.
    • Do this by specificing type attribute type="XXX".
  • Text Area:
    • Text area element provides an input box that can accept text that spans multiple lines like user comments and reviews.
    • Resizable by clicking and dragging the bottom right corner to make it bigger or smaller.
    • Text area element: <textarea>Some initial content</textarea>. Has closing tag, allows wrapping some initial content.
    • Has some attributes: <textarea rows="20" cols="60"></textarea>

Selection Elements

Concerned with selecting a value from a predefined list.

  • Select dropdown:
    1
    2
    3
    4
    
    <select name="Car">
    <option value="audi" selected>Mercedes</option>
    <option value="tesla">Tesla</option>
    </select>
    
    • We can also split list of option into groups using <optgroup> element.
  • Radio Buttons ```html

Ticket Type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  * Use same `name` attribute for a group of options.

* Checkboxes
```html
<h1>Pizza Toppings</h1>

<div>
  <input type="checkbox" id="sausage" name="topping" value="sausage">
  <label for="sausage">Sausage</label>
</div>

<div>
  <input type="checkbox" id="onions" name="topping" value="onions">
  <label for="onions">Onions</label>
</div>

Buttons

Clickable buttons that users can interact with to submit forms and trigger other actions. Three types of buttons.

  • Submit Buttons
  • Reset Buttons
  • Generic Buttons (Commonly used with JS for interactivity)
1
2
3
4
<button>Click Me</button>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
<button type="button">Click to Toggle</button>

Tip: Button within a form with the type value of submit (which happens to be the default value) will always try to make a new request and submit data back to the server. Hence, for buttons that are used within a form for different purposes other than submitting the data, the type attribute should always be specified to avoid unwanted effects of submitting a form.

Organizing Form Elements

If there are many inputs, organization into sections that are visually distinct and manageable to digest is important.

  • Fieldset element
    • Container element that allows grouping related form inputs into one logical unit.
1
2
3
4
5
6
7
<fieldset>
  <label for="first_name">First Name</label>
  <input type="text" id="first_name" name="first_name">

  <label for="last_name">Last Name</label>
  <input type="text" id="last_name" name="last_name">
</fieldset>
  • Legend
    • Used to give field sets a heading or caption so user can see what a grouping of inputs is for.
    • Common-use case is using a fieldset to group radio buttons and using a legend to tell what each option ultimately for.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<fieldset>
  <legend>Contact Details</legend>

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

  <label for="phone_number">Phone Number:</label>
  <input type="tel" id="phone_number" name="phone_number">

  <label for="email">Email:</label>
  <input type="email" id="email" name="email">
</fieldset>

<fieldset>
  <legend>What would you like to drink?</legend>

  <div>
    <input type="radio" name="drink" id="coffee" value="coffee">
    <label for="coffee">Coffee</label>
  </div>

  <div>
    <input type="radio" name="drink" id="tea" value="tea">
    <label for="tea">Tea</label>
  </div>

  <div>
    <input type="radio" name="drink" id="soda" value="soda">
    <label for="soda">Soda</label>
  </div>
</fieldset>

Styling Forms

Some of the challenges with styling HTML forms and how we can get around them:

  • Default browser styles
    • Each browser has own default styles for form controls, making forms visually different for users depending on browser used.
    • To have a consistent design among all browsers, we have to override these default styles and style them ourselves.
  • Tricky and downright impossible to style form controls
    • Text-based form controls like text, email, password and text areas are reasonably straightforward to style. They operate like any other HTML element, and most CSS properties can be used on them.
    • However, creating custom styles for radio buttons and checkboxes is tricky. Many guides available to achieve your desired design.
    • There have also been new CSS properties made available in recent times to make styling radio buttons and checkboxes much easier.
  • Certain aspects of other elements are downright impossible to style, for example, calendar or date pickers.
    • If we want custom styles for these, we will have to build custom form controls with JavaScript or use one of the many JavaScript libraries that provide us with ready-made solutions.

Form Validation

Validations allow us to set specific constraints or rules on data users can enter into an input. They protect backend systems from receiving incorrect data and help make experience of interacting with our form simple. Following are some built-in validations we can use with HTML forms and styling variations with CSS.

Some Types of Validation

  • Required Validation
    • Ensure specific fields are filled before submitting the form.
    • Add required attribute to an <input>
    • Good practice to add asterisk(*) to required field labels.
  • Text length Validations
    • Enter a minimum or a maximum amount of text into a field.
    • Add minlength="X" and/or maxlength="Y" attribtue with number of characters.
  • Number Range Validations
    • Control range of values users can enter into number based form controls.
    • Use min="1" or max attributes to do so.
  • Pattern Validation
    • Ensure data matches a particular pattern. (e.g. cashcard, zipcode)
    • Add pattern attribute with a regular expression.
    • Good practice to use a placeholder attribute to show expected pattern
1
<input type="text" id="zip_code" name="zip_code" pattern="(\d{5}([\-]\d{4})?)" title="Please enter a valid zip code, example: 65251" placeholder="65251" required>

Styling Validations

We can target form controls that have passed or failed validations using the :valid and :invalid pseudo-classes.

E.g. we target any valid inputs and give them a green border, and when a field is invalid, we give it a red border instead.

Sometimes, will need to include validations that built-in validations won’t be able to do.

  • E.g. validating a password input and password confirmation input have the same value or validating that a username has not already been taken.
  • We can make custom validations using JS and CSS.
This post is licensed under CC BY 4.0 by the author.