Categories
HTML Tutorials

Grouping form elements together

As you build more complex forms, it can be convenient to group some of the elements together, which you can do using the fieldset element. You can see how the fieldset element is applied below. We added additional input elements to this example to demonstrate that a fieldset can be applied to a subset of the elements in a form.

Using the fieldset element
<html>
  <head>
    <title>Example</title>
    <meta name="author" content="Adam Freeman"/>
    <meta name="description" content="A simple example"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  </head>
  <body>
    <form method="post" action="http://titan:8080/form">
      <fieldset>
        <p><label for="name">Name: <input id="name" name="name"/></label></p>
        <p><label for="name">City: <input id="city" name="city"/></label></p>
      </fieldset>
      <fieldset>
        <p><label for="fave1">#1: <input id="fave1" name="fave1"/></label></p>
        <p><label for="fave2">#2: <input id="fave2" name="fave2"/></label></p>
        <p><label for="fave3">#3: <input id="fave3" name="fave3"/></label></p>
      </fieldset>
      <button>Submit Vote</button>
    </form>
  </body>
</html>

We used a fieldset element to group together two input elements that gather details about the user, and another fieldset to group three input elements that allow the user to vote for his/her three favorite fruits. You can see how the browser shows the default style convention for the fieldset element below.

Adding a descriptive label to a fieldset element

You grouped your input elements together, but you still lack context for the user. You can remedy this by adding a legend element to each of your fieldset elements.

<html>
  <head>
    <title>Example</title>
    <meta name="author" content="Adam Freeman"/>
    <meta name="description" content="A simple example"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  </head>
  <body>
    <form method="post" action="http://titan:8080/form">
      <fieldset>
        <legend>Enter Your Details</legend>
        <p><label for="name">Name: <input id="name" name="name"/></label></p>
        <p><label for="name">City: <input id="city" name="city"/></label></p>
      </fieldset>
      <fieldset>
        <legend>Vote For Your Three Favorite Fruits</legend>
        <p><label for="fave1">#1: <input id="fave1" name="fave1"/></label></p>
        <p><label for="fave2">#2: <input id="fave2" name="fave2"/></label></p>
        <p><label for="fave3">#3: <input id="fave3" name="fave3"/></label></p>
      </fieldset>
      <button>Submit Vote</button>
    </form>
  </body>
</html>

You can see how the browser displays the legend elements below.