CodeGym /Curso de Java /Frontend SELF ES /Agrupación de elementos de formulario

Agrupación de elementos de formulario

Frontend SELF ES
Nivel 8 , Lección 4
Disponible

4.1 Elemento <fieldset>

Agrupar elementos de formulario permite unir lógicamente los elementos relacionados, lo que mejora la estructura del formulario y lo hace más conveniente para los usuarios. HTML proporciona dos etiquetas para agrupar elementos de formulario: <fieldset> y <legend>.

El elemento <fieldset> se utiliza para agrupar elementos de formulario relacionados dentro de <form>. Visualmente este elemento suele mostrarse como un marco alrededor de los elementos agrupados, lo que ayuda al usuario a entender qué campos pertenecen a un grupo.

Ejemplo de uso:

En este ejemplo vemos dos grupos de elementos de formulario: "Personal Information" y "Account Details", cada uno rodeado por el elemento <fieldset> y provisto con un encabezado <legend>.

HTML
    
      <form action="/submit" method="post">
        <fieldset>
          <legend>Personal Information</legend>
          <label for="name">Name:</label>
          <input type="text" id="name" name="name" required>
          <label for="email">Email:</label>
          <input type="email" id="email" name="email" required>
        </fieldset>
        <fieldset>
          <legend>Account Details</legend>
          <label for="username">Username:</label>
          <input type="text" id="username" name="username" required>
          <label for="password">Password:</label>
          <input type="password" id="password" name="password" required>
        </fieldset>
        <button type="submit" id="submit">Submit</button>
      </form>
      <script>
        const inputs = document.getElementsByTagName("input");
        const submit = document.getElementById("submit");

        submit.addEventListener("click", (e) => {
          e.preventDefault();

          const values = [];
          let allValid = true;

          for (let input of inputs) {
            if (!input.validity.valid) {
              allValid = false;
              break;
            }
            values.push(input.value);
          }

          if (allValid) {
            alert(
              "Personal Information:\n" +
              `Name: ${values[0]}\n` +
              `Email: ${values[1]}\n\n` +
              "Account Details:\n" +
              `Username: ${values[2]}\n` +
              `Password: ${values[3]}`
            );
          } else {
            alert("Por favor, completa todos los campos");
          }
        });
      </script>
    
  
HTML
    
      <form>
        <fieldset>
          <legend>Personal Information</legend>
          <label for="name">Name:</label>
          <input type="text" id="name" name="name">
          <label for="email">Email:</label>
          <input type="email" id="email" name="email">
        </fieldset>
        <fieldset>
          <legend>Account Details</legend>
          <label for="username">Username:</label>
          <input type="text" id="username" name="username">
          <label for="password">Password:</label>
          <input type="password" id="password" name="password">
        </fieldset>
        <input type="submit" value="Submit">
      </form>
    
  

Atributos principales de <fieldset>:

Atributo disabled: hace que todos los elementos dentro de <fieldset> sean inaccesibles para el usuario (no pueden ser modificados y no se enviarán al servidor).

HTML
    
        <fieldset disabled>
          <legend>Disabled Group</legend>
          <label for="disabled-field">This field is disabled:</label>
          <input type="text" id="disabled-field" name="disabled-field">
        </fieldset>
    
  

4.2 Elemento <legend>

El elemento <legend> se utiliza para añadir un encabezado a un grupo de elementos creado con <fieldset>. Ayuda al usuario a entender el propósito y contexto del grupo de campos del formulario.

Ejemplo de uso:

HTML
    
        <fieldset>
          <legend>Contact Information</legend>
          <label for="phone">Phone Number:</label>
          <input type="tel" id="phone" name="phone">
          <label for="address">Address:</label>
          <input type="text" id="address" name="address">
        </fieldset>
    
  

Características del elemento <legend>:

  1. Ubicación: el elemento <legend> siempre se coloca dentro de <fieldset>, y su posición generalmente se encuentra en la parte superior del marco.
  2. Texto: el texto dentro de <legend> describe el grupo de campos del formulario, lo que ayuda a los usuarios a orientarse rápidamente en el formulario.

Consejos útiles para usar <fieldset> y <legend>

  • Agrupación lógica: usa <fieldset> y <legend> para la agrupación lógica de los elementos del formulario — esto hará que el formulario sea más organizado y comprensible para el usuario
  • Accesibilidad: los elementos <fieldset> y <legend> mejoran la accesibilidad del formulario, ayudando a los usuarios que utilizan tecnologías asistidas a entender la estructura y el contenido del formulario
  • Estilo y formato: utiliza CSS para estilizar <fieldset> y <legend> para mejorar el aspecto del formulario

4.3 Ejemplos de uso de <fieldset> y <legend>

Formulario de registro con agrupación de campos:

HTML
    
      <form form action="/submit" method="post">
        <fieldset>
          <legend>Personal Details</legend>
          <label for="fname">First Name:</label>
          <input type="text" id="fname" name="fname" required>
          <label for="lname">Last Name:</label>
          <input type="text" id="lname" name="lname" required>
        </fieldset>
        <fieldset>
          <legend>Login Information</legend>
          <label for="username">Username:</label>
          <input type="text" id="username" name="username" required>
          <label for="password">Password:</label>
          <input type="password" id="password" name="password" required>
        </fieldset>
        <button type="submit" id="submit">Submit</button>
      </form>
      <script>
        const inputs = document.getElementsByTagName("input");
        const submit = document.getElementById("submit");

        submit.addEventListener("click", (e) => {
          e.preventDefault();

          const values = [];
          let allValid = true;

          for (let input of inputs) {
            if (!input.validity.valid) {
              allValid = false;
              break;
            }
            values.push(input.value);
          }

          if (allValid) {
            alert(
              "Personal Details:\n" +
              `First name: ${values[0]}\n` +
              `Last Name: ${values[1]}\n\n` +
              "Login information:\n" +
              `Username: ${values[2]}\n` +
              `Password: ${values[3]}`
            );
          } else {
            alert("Por favor, completa todos los campos");
          }
        });
      </script>
    
  
HTML
    
      <form>
        <fieldset>
          <legend>Personal Details</legend>
          <label for="fname">First Name:</label>
          <input type="text" id="fname" name="fname">
          <label for="lname">Last Name:</label>
          <input type="text" id="lname" name="lname">
        </fieldset>
        <fieldset>
          <legend>Login Information</legend>
          <label for="username">Username:</label>
          <input type="text" id="username" name="username">
          <label for="password">Password:</label>
          <input type="password" id="password" name="password">
        </fieldset>
        <input type="submit" value="Register">
      </form>
    
  

Formulario con diferentes tipos de datos:

HTML
    
      <form action="/auth" method="post">
        <fieldset>
          <legend>Contact Information</legend>
          <label for="email">Email:</label>
          <input type="email" id="email" name="email" required>
          <label for="phone">Phone Number:</label>
          <input type="tel" id="phone" name="phone" required>
        </fieldset>
        <fieldset>
          <legend>Preferences</legend>
          <label for="newsletter">Subscribe to newsletter:</label>
          <input type="checkbox" id="newsletter" name="newsletter">
          <label for="updates">Receive updates:</label>
          <input type="checkbox" id="updates" name="updates">
        </fieldset>
        <button type="submit" id="submit">Submit</button>
      </form>
      <script>
        const form = document.querySelector("form");
        const inputs = form.querySelectorAll("input");
        const submit = document.getElementById("submit");

        submit.addEventListener("click", (e) => {
          e.preventDefault();

          let email = "";
          let phone = "";
          let newsletter = 0;
          let updates = 0;
          let allValid = true;

          inputs.forEach((input) => {
            if (input.type === "email" && (!input.validity.valid)) {
              allValid = false;
            } else if (input.type === "tel" && (!input.validity.valid)) {
              allValid = false;
            }

            if (input.type === "email") {
              email = input.value;
            } else if (input.type === "tel") {
              phone = input.value;
            } else if (input.type === "checkbox") {
              if (input.id === "newsletter") {
                newsletter = input.checked ? 1 : 0;
              } else if (input.id === "updates") {
                updates = input.checked ? 1 : 0;
              }
            }
          });

          if (allValid) {
            alert(
              "Contact Information\n" +
              `Email: ${email}\n` +
              `Phone Number: ${phone}\n\n` +
              "Preferences\n" +
              `Subscribe to newsletter: ${newsletter}\n` +
              `Receive updates: ${updates}`
            );
          } else {
            alert("Los campos Email y Phone deben ser completados");
          }
        });
      </script>
    
  
HTML
    
      <form>
        <fieldset>
          <legend>Contact Information</legend>
          <label for="email">Email:</label>
          <input type="email" id="email" name="email">

          <label for="phone">Phone Number:</label>
          <input type="tel" id="phone" name="phone">
        </fieldset>
        <fieldset>
          <legend>Preferences</legend>
          <label for="newsletter">Subscribe to newsletter:</label>
          <input type="checkbox" id="newsletter" name="newsletter">
          <label for="updates">Receive updates:</label>
          <input type="checkbox" id="updates" name="updates">
        </fieldset>
        <input type="submit" value="Submit">
      </form>
    
  
CSS
    
      fieldset {
        border: 2px solid #ccc;
        padding: 20px;
      }

      legend {
        font-weight: bold;
        padding: 0 10px;
      }
    
  
Comentarios
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION