HTML5 tables, forms and input fields

July 05, 2017


The HTML table JavaScript API: dynamic tables!

Introduction

There is a JavaScript API associated with the HTML table elements that makes dynamic table management possible, enabling you to add or delete a row, add or delete a cell, modify the content of the cells, etc.

The Table object (<table>)

When you look for a table using the DOM API or the selector API, or when you create a table using the DOM API, you get a Table object:

1
2
3
4
5
var table = document.getElementById("myTable");

var table = document.querySelector("#myTable");

var table = document.createElement("table"); // creates a new table

Like all objects, an instance of Table will have properties and methods:

Most useful properties
rows Returns a collection of all <tr> elements in a table
caption Returns the <caption> element of a table
tFoot Returns a reference to the <tfoot> element of a table
tHead Returns a reference to the <thead> element of a table
Most useful methods
insertRow() Creates an empty <tr> element and adds it to the table. Example: var row = table.insertRow(); inserts a new row at the end of the table. var row = table.insertRow(0); inserts at index = 0, var row = table.insertRow(10); inserts at index = 10, and pushes all the rows after this index.
deleteRow() Removes a row (<tr>) from the table. Example table.deleteRow(0); deletes the row at index 0.
createCaption() Creates an empty <caption> element and adds it to the table
deleteCaption() Removes the first <caption> element from the table
createTHead() Creates an empty <thead> element and adds it to the table
deleteTHead() Removes the <thead> element from the table
createTFoot() Creates an empty <tfoot> element and adds it to the table
deleteTFoot() Removes the <tfoot> element from the table



Example:

A typical HTML table
Given Name Family Name Age
Michel Buffa 52
Dark Vador Unknown
Luke Skywalker Unknown

Click to add a new row

Click to delete the first row of the table

Notice the use of row.innerHTML= here to add some cells to the row. We will soon see another method for doing this.

The TableRow object (<tr>)

When you look for a row using the DOM API or the selector API, or when you create a row using the DOM API, you get a Row object:

1
2
3
4
5
var row1 = document.getElementById("row1");

var row1 = document.querySelector("#row1");

var newRow = document.createElement("row"); // creates a new row

You can also access a row from the rows property of a table:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  
> var t = document.createElement("table");
undefined

> var r1 = t.insertRow(0);
undefined

> r1.innerHTML="<td>Hello</td>";
"<td>Hello</td>"

> var r2 = t.insertRow();
undefined

> r2.innerHTML="<td>Hello 2</td>";
"<td>Hello 2</td>"

> var row1 = t.rows[0];
undefined

> row1;
<tr><td>Hello</td></tr>

Like all objects, a TableRow object has properties and methods. Here are the most useful ones:

Most useful properties
cells Returns a collection of all <td> or <th> elements in a table row
rowIndex Returns the position of a row in the rows collection of a table
sectionRowIndex Returns the position of a row in the rows collection of a <tbody>, <thead>, or <tfoot>
Most useful methods
insertCell() Inserts a cell into the current table row. Without parameters, appends a cell after the last cell of the row. You can pass the index of the cell as a unique parameter, in which case other cells are "pushed" to the right. The value of 0 results in the new cell being inserted at the first position. The value of -1 can also be used, which results in the new cell being inserted in the last position.
deleteCell() Deletes a cell from the current table row. There is one parameter for this method: the index of the cell to remove. The value of 0 results in the deletion of the first cell. The value of -1 can also be used, which results in the deletion of the last cell.



Example

A typical HTML table
Given Name Family Name Age
Michel Buffa 52
Dark Vador Unknown
Luke Skywalker Unknown

Click to add a new row

Click to delete the first row of the table

Notice how we’ve created the new row cells:
1
2
3
4
5
6
7
8
9
10
11
12
13
  
  function insertRow() {
      var table = document.querySelector("#myTable");
      // without parameters, insert at the end,
      // otherwise parameter = index where the row will be inserted
      var row = table.insertRow();
      var cell1 = row.insertCell();
      cell1.innerHTML = "New cell1";
      var cell2 = row.insertCell();
      cell2.innerHTML = "New cell2";
      var cell3 = row.insertCell();
      cell3.innerHTML = "New cell3";
  }

So use insertCell() or just row.innerHTML=”<td>…</td>” ? It’s up to you: depending on the HTML that you plan to insert into each cell, one version may be more readable than the other.


HTML forms: best practices

1 - Creating accessible forms

Forms are commonly used to enable user interaction within Web sites and Web applications, for example, for login, registering, commenting, and purchasing.

Since HTML5 provides functionalities to assist with accessibility, developers should make a concerted effort to mark up Web based forms. The following two guidelines are to give you a good start to make your forms accessible:

  • 1. For every form field, ensure that a descriptive label is provided and use the <label> element to identify each form control.
  • 2. For larger or complex forms, use the <fieldset> and <legend> elements to respectively group and associate related form controls.

We will give usage examples for each of these two basic guidelines in the following pages.

Further reading

The WAI Web site hosts a Forms tutorial where you will find more guidelines to help make your forms truly accessible: Form Instructions, Validating Input, User Notifications,

2 - Why is this important?

Forms can be visually and cognitively complex and difficult to use. Accessible forms are easier to use for everyone, including people with disabilities.

  • People with cognitive disabilities can more easily understand the form and how to complete it, as making forms accessible improves the layout structure, instructions, and feedback.
  • People using speech input can use the labels via voice commands to activate controls and move the focus to the fields that they need to complete.
  • People with limited dexterity benefit from large clickable areas that include the labels, especially for smaller controls, such as radio buttons and checkboxes.
  • People using screen readers can identify and understand form controls more easily because they are associated with labels, field sets, and other structural elements.
3 - Labeling controls

Labels need to describe the purpose of the form control

Form fields and other form controls usually have visible labels, such as “E-mail Address:” as the label for a text field (see figure below).

When these labels are marked up correctly, people can interact with them using only the keyboard, using voice input, and using screen readers. Also, the label itself becomes clickable, which enables a person who has difficulty clicking on small radio buttons or checkboxes to click anywhere on the label text.

Associating labels explicitly

Whenever possible, use the label element to explicitly associate text with form elements. The for attribute of the label must exactly match the id of the form control.

Example 1 (click on the label, not on the input field to see the effect)

Source code:

1
2
<label for="first_name">Your First Name</label>
<input id="first_name" type="text" name="fname"/>

Alternative example 1

Note that you can also include the element inside the element, and also add a for example, to indicate the language used in the label. Sometimes, nesting labels and inputs can also make CSS styling easier and produce better results with screen readers.

Source code (with inside the

1
2
3
<label for="first_name"><span lang=en">Your First Name</span>
    <input id="first_name" type="text" name="fname"/>
</label>

Example 2 (click on the label “Subscribe to newsletter” to see the effect)


Source code:

1
2
3
4
<label for="firstname">First name:</label>
<input type="text" name="firstname" id="firstname"><br>
<label for="subscribe">Subscribe to newsletter</label>
<input type="checkbox" name="subscribe" id="subscribe">
4 - Labeling buttons

The label of a <button> element is set inside the element and can include markup. This allows advanced accessibility hints to be included, such as marking up language change.

Example: <button>Mon <span lang=”fr”>bouton</span></button>, for a button with a label in French.

When using the <input> element to create buttons, the label is set in the value attribute of the element.

Example: <input type=”submit” value=”Please submit”>, will be rendered as a button.

Source code for an example of “Submit” and “Cancel” buttons:

1
2
3
4
5
<button type="submit">Submit</button>
<button type="button">Cancel</button>

<input type="submit" value="Submit">
<input type="button" value="Cancel">

These will produce the same results:

Lines 1 and 2 render as:

While lines 3 and 4 render as:

5 - Labeling text areas


Source code:

1
2
3
<label for="address">Enter your address:</label>
<br>
<textarea id="address" name="addresstext"></textarea>
6 - Grouping controls

Groupings of form controls, typically groups of related checkboxes and radio buttons, sometimes require a higher level description. Grouping related form controls makes forms more understandable for all users, as related controls are easier to identify.

Associating related controls with fieldset

Grouping needs to be carried out visually and in the code, for example, by using the <fieldset> and <legend> elements to associate related form controls. The <fieldset> identifies the entire grouping and <legend> identifies the grouping’s descriptive text.

Example 1 - Radio buttons

In the example below, there are three radio buttons that allow the user to choose an output format. Radio button groups should always be grouped using <fieldset>.

Output format

Source code:

1
2
3
4
5
6
7
8
9
10
11
12
<fieldset>
   <legend>Output format</legend>
      <div>
         <input type="radio" name="format" id="txt" value="txt" checked>
         <label for="txt">Text file</label>
      </div>
   <div>
      <input type="radio" name="format" id="csv" value="csv">
      <label for="csv">CSV file</label>
   </div>
[]
</fieldset>

Example 2 - Checkboxes

In the example below, there are three checkboxes that are all part of an opt-in function for receiving different types of information.

I want to receive

Source code:

1
2
3
4
5
6
7
8
<fieldset>
   <legend>I want to receive</legend>
   <div>
      <input type="checkbox" name="newsletter" id="check_1">
      <label for="check_1">The weekly newsletter</label>
   </div>
   []
</fieldset>

WAI-ARIA provides a grouping role that functions in a similar way to fieldset and legend. For example, a div element can have role=group to indicate that the contained elements are members of a group.

WAI-ARIA roles are very important in the accessibility world, and we invite you to see an example provided in the associated WAI tutorial. This article by Oscar Cao gives an Introduction to understanding WAI-ARIA 1.0 roles.

HTML forms and JavaScript

Introduction

Forms are a way to get user input which is either sent to a remote server, or processed locally, or both.

This section of the course will only cover local processing and the client-side part, with a focus on JavaScript processing.

Typical example

Personal informations



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
<form id="myForm">
  <fieldset>
    <legend>Personal informations</legend>

    <label for="givenName">Given name:</label>
    <input type="text" id="givenName" required name="givenName">

    <br>

    <label for="familyName">Family name:</label>
    <input type="text" id="familyName" required name="familyName">

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

     <br>
     <label for="age">Age:</label>
    <input type="number" min=0 max=120  step=5 id="age" required name="age">

         <br>
     <label for="date">Birth date:</label>
    <input type="date"  id="date" required name="date">
  </fieldset>

  <button>Submit form</button>
  </form>
  
HTML form input can be sent to a server without JavaScript

If a form’s content is sent to a remote server, on the server side, you may have PHP, Java, C#, Ruby, Python, etc. components. There are several ways to collect server-side data from a form in a Web page: REST Web services, servlets, Microsoft ASP pages, etc.

On the client side, the forms indicate to which server and how the data should be sent, using the action and method attributes respectively. A <button type=”submit”> or an <input type=submit> field is used to submit the form content.

For example: <form action=”myServerCode.php” method=”POST”>…</form>. Here, we set the URL of the server side code (myServerCode.php), and the HTTP method that will be used by the browser for sending the form content (POST).

Example of HTML5 form that will not be sent if invalid input fields are present. Notice that the JavaScript part is only used for giving feedback while entering the password. No JavaScript is used for sending the form data, or for complex, global validation:

The bits I need to make you join my forum



Random bits I don't need, I'm just curious


Answer me these questions three


Sanity checks
1
HTML form input can be sent using Ajax / JavaScript

Another approach is to use JavaScript for sending the form content with Ajax. This will be covered in the JavaScript advanced course, to be be available on W3Cx.

JavaScript can be used for validating user input “on the fly”

While one is typing or selecting a color, or moving a slider, JavaScript event listeners can be used to track the user’s interactions in real time, and perform some validation steps along with giving visual feedback.

We’ve already seen how we can track the keys typed in an input field in real time:

Simple input field validation using the 'input' event

Just type a name in the input field and see what happens! TRY TO TYPE A "!" too

JavaScript can be used for a more global validation before sending a form to a remote server

Example: checking that a password entered twice is identical in two different input fields, that some values are coherent (e.g. a birthday cannot be in the future), etc.

Example use of the validation API:
try to submit with different passwords,
and with same passwords

JavaScript can be used to make a WebApp that uses form data locally, perhaps with some client-side persistence API

For example, a contact manager that will work offline, saving data locally, in a database inside the browser. Data will be displayed in a dynamic HTML table, without the need for a remote database.

This is the small project we will build together at the end of the course. :-)