Wednesday, 19 February 2025

Organizing Forms with HTML Fieldset and Legend Elements

The <fieldset> and <legend> elements in HTML are used together to group related form controls and label them. They help to improve the structure and accessibility of forms by providing a clear division and description of different sections within a form.

The <legend> element is used to provide a caption or title for the content within the <fieldset>. It usually appears at the top of the grouped section and describes the group of form elements for better clarity.

 

fieldset.html 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>datalist Example</title>
  </head>

  <body>
    <form action="https://httpbin.org/post" method="POST">
      <fieldset>
        <legend>Personal Information</legend>

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

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

      <fieldset style="margin-top: 30px">
        <legend>Preferences</legend>

        <p><label for="contact">Preferred Contact Method:</label>
        <select id="contact" name="contact">
          <option value="email">Email</option>
          <option value="phone">Phone</option>
        </select></p>

        <p><label for="subscribe">Subscribe to newsletter:</label>
        <input type="checkbox" id="subscribe" name="subscribe" /></p>
      </fieldset>

      <input type="submit" value="Submit" style="margin-top: 20px"/>
    </form>
  </body>
</html>

Above snippet generate below screen.


 

The first <fieldset> groups the "Personal Information" fields (name and email). The <legend> describes that this section contains personal details. The second <fieldset> groups the "Preferences" fields (preferred contact method and subscription to a newsletter), with a relevant <legend>.

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment