Chapter 8

Tables and Forms

Learn to lay out data in HTML tables and collect user input with well structured forms.

Tables and Forms

Tables display data in rows and columns, and forms collect input from the person using your page. Both are built from a small set of HTML5 tags. This lesson shows the correct structure for each so your markup stays accessible and easy to style.

Building a table

A table is made of rows (<tr>) that hold header cells (<th>) or data cells (<td>). Wrap the header row in <thead> and the data rows in <tbody>. A <caption> names the table for everyone, including screen readers.

<table>
  <caption>Stationery prices</caption>
  <thead>
    <tr><th>Item</th><th>Price</th></tr>
  </thead>
  <tbody>
    <tr><td>Pen</td><td>RM2</td></tr>
    <tr><td>Ruler</td><td>RM3</td></tr>
  </tbody>
</table>

Use colspan to make one cell span several columns, and rowspan to span several rows. Tables are for tabular data only, never for page layout.

Building a form

A <form> wraps the controls. Its action attribute is the URL that receives the data, and method is usually get or post. Every control should have a <label> whose for value matches the control id, so clicking the label focuses the field.

<form action='/signup' method='post'>
  <label for='name'>Name</label>
  <input id='name' name='name' type='text'>

  <label for='age'>Age</label>
  <input id='age' name='age' type='number'>

  <label for='bio'>About you</label>
  <textarea id='bio' name='bio'></textarea>

  <button type='submit'>Send</button>
</form>

Input types

The type attribute changes how an <input> behaves: text, email, password, number, checkbox, radio, date and more. The name attribute is the key sent to the server; without it the value is not submitted. Radio buttons that share the same name form a group where only one can be chosen.

Use <select> with <option> children for a drop-down list, and add required to force a field to be filled before submitting.

Grouping and accessibility

Wrap related controls in a <fieldset> and give the group a title with <legend>. This helps everyone understand which fields belong together, and it is especially useful for a set of radio buttons or checkboxes.

<fieldset>
  <legend>Meal choice</legend>
  <label><input type='radio' name='meal' value='veg'> Vegetarian</label>
  <label><input type='radio' name='meal' value='fish'> Fish</label>
</fieldset>

Inside a table, add scope='col' or scope='row' to header cells so screen readers know whether a header describes a column or a row. Small touches like these make your pages usable for people using assistive technology, and they cost almost nothing to add.

Remember: Always pair each form control with a matching label using for and id. It makes forms usable for everyone and gives you a reliable hook for CSS.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor