Saltar al contenido

Formularios HTML

Un formulario HTML está compuesto por elementos de formulario, que son distintos tipos de elementos de entrada, como casillas de verificación, campos de texto, botones de envío, botones de opción, y así sucesivamente.

El elemento HTML <input>

El elemento <input> es un elemento de formulario esencial que, según el atributo type, puede mostrarse de diferentes maneras.

Hablemos de algunos tipos de entrada.

Entrada de texto

El <input type="text"> especifica un campo de entrada de una sola línea para introducir texto.

Ejemplo de la entrada de texto:

html
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h2>Text Input Example</h2>
    <form>
      Name:<br />
      <input type="text" name="name" />
      <br />
      Surname:<br />
      <input type="text" name="surname" />
    </form>
  </body>
</html>

Entrada de botón de opción

El <input type="radio"> especifica un botón de opción con el que puedes seleccionar una de varias opciones.

Ejemplo de la entrada de botón de opción

html
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h2>Radio Button Example</h2>
    <form>
      <input type="radio" name="game" value="football" checked /> Football
      <input type="radio" name="game" value="basketball" /> Basketball
    </form>
  </body>
</html>

Entrada de envío

El <input type="submit"> envía los datos del formulario a un procesador de formularios.

El procesador de formularios es una página del servidor con un script para procesar los datos de entrada, que se define en el atributo action del formulario.

Ejemplo de la entrada de envío

html
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h2>HTML Form Example</h2>
    <form action="/form/submit" method="POST">
      Name:<br />
      <input type="text" name="firstname" value="Tom" />
      <br />
      Surname:<br />
      <input type="text" name="lastname" value="Brown" />
      <br />
      Age:<br />
      <input type="text" name="Age" value="21" />
      <br /><br />
      <input type="submit" value="Submit" />
    </form>
    <p>Click the "Submit" button to send the form data to the action page.</p>
  </body>
</html>

El atributo Action

El atributo action especifica la acción que debe realizarse cuando se envía el formulario.

Cuando el usuario hace clic en el botón de envío, los datos del formulario se envían a una página web del servidor.

Formularios HTML

html
<form action="/form/submit">

El atributo Target

El atributo target define si el resultado del formulario se abrirá en una nueva pestaña del navegador, en un marco o en la ventana actual.

El valor predeterminado de este atributo es _self. Usar este valor abrirá el resultado del formulario en la ventana actual.

El valor _blank abrirá el resultado del formulario en una nueva pestaña del navegador.

Formularios HTML

html
<form action="/form/submit" target="_blank">

El atributo Method

El atributo method define el método HTTP (GET o POST) que se usará al enviar los datos del formulario.

Ejemplo del método GET:

Ejemplo del método GET

html
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h2>The method Attribute With the GET Method</h2>
    <form action="/form/submit" target="_blank" method="GET">
      Name:<br />
      <input type="text" name="name" value="Tom" />
      <br />
      Surname:<br />
      <input type="text" name="Surname" value="Brown" />
      <br />
      Age:<br />
      <input type="number" name="age" value="21" />
      <br /><br />
      <input type="submit" value="Submit" />
    </form>
    <p> Here we used the "_blank" value, which will open the form result in a new browser tab.</p>
  </body>
</html>

Ejemplo del método POST:

Ejemplo del método POST:

html
<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h2>The method Attribute With the Post Method</h2>
    <form action="/form/submit" target="_blank" method="POST">
      Name:<br />
      <input type="text" name="name" value="Tom" />
      <br />
      Surname:<br />
      <input type="text" name="surname" value="Brown" />
      <br />
      Age:<br />
      <input type="number" name="age" value="21" />
      <br /><br />
      <input type="submit" value="Submit" />
    </form>
  </body>
</html>

Cuándo usar el método GET

GET es el método predeterminado al enviar datos de formulario, y cuando se usa este método los datos del formulario son visibles en el campo de dirección de la página.

DANGER

No uses el método GET para enviar datos sensibles, porque serán visibles en la URL.

TIP

El método GET es útil para envíos de formularios en los que el usuario quiere guardar el resultado en marcadores.

DANGER

La longitud de una URL es limitada (máximo 2048 caracteres).

Cuándo usar el método POST

Si los datos del formulario incluyen información sensible o personal, usa siempre el método POST, ya que no muestra los datos enviados del formulario en el campo de dirección de la página.

TIP

Como no hay limitaciones de tamaño al usar el método POST, puede utilizarse para enviar grandes cantidades de datos.

Los envíos de formularios con el método POST no se pueden guardar en marcadores.

Otros atributos

A continuación puedes encontrar otros atributos de <form>:

AttributeDescription
accept-charsetThis attribute defines the charset that is used in the submitted form (default: the page charset).
autocompleteThis attribute defines whether the browser should autocomplete the form or not (default: on).
enctypeThis attribute defines the encoding of the submitted data (default:url-encoded).
nameThis attribute defines a name that is used to identify the form.
novalidateThis attribute defines that the browser must not validate the form.

Práctica

What are the essential attributes that every HTML form input element should include?

¿Te resulta útil?

Vista previa dual-run — compárala con las rutas Symfony en producción.