diff --git a/README.es.md b/README.es.md index 78932c8..1c2f506 100644 --- a/README.es.md +++ b/README.es.md @@ -1,85 +1,193 @@ -# Tutorial & Ejercicios de Formularios HTML5 +
- +# Aprende cómo usar e interactuar con Formularios en HTML -> Por [@alesanchezr](https://twitter.com/alesanchezr) y [otros colaboradores](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/graphs/contributors) de [4Geeks Academy](https://4geeksacademy.co/) +[![Tutorial interactivo](https://img.shields.io/badge/4Geeks-Tutorial_interactivo-2563eb?style=for-the-badge)](https://4geeks.com/es/interactive-exercise/forms-exercises-es) +[![8 ejercicios con LearnPack](https://img.shields.io/badge/LearnPack-8_ejercicios-2563eb?style=for-the-badge)](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/tree/HEAD/exercises) +[![Abrir en Codespaces](https://img.shields.io/badge/Abrir_en-Codespaces-fb5a1f?style=for-the-badge&logo=github)](https://github.com/codespaces/new/?repo=4GeeksAcademy/html-forms-tutorial-exercises) -![last commit](https://img.shields.io/github/last-commit/4geeksacademy/html-forms-tutorial-exercises) -[![build by developers](https://img.shields.io/badge/build_by-Developers-blue)](https://breatheco.de) -[![build by developers](https://img.shields.io/twitter/follow/4geeksacademy?style=social&logo=twitter)](https://twitter.com/4geeksacademy) +![Portada del tutorial: una hoja de papel con la palabra HTML5 en gris oscuro sobre la palabra FORMS en naranja, el subtítulo Interactive Tutorial, un pequeño icono de un formulario con casillas y una franja negra al pie que dice time to code](https://raw.githubusercontent.com/4GeeksAcademy/html-forms-tutorial-exercises/master/.learn/assets/preview.png) +
-Los formularios son tan importantes en el mundo de HTML, CSS y JavaScript que decidí dedicarles un tutorial especial para enfocarme en todas las entradas/inputs, botones y elementos que HTML trae por defecto para centrarme en la interacción. En estos ejercicios aprenderás: +Este tutorial de LearnPack cubre los formularios de HTML5 en 8 pasos: un vídeo de introducción y 7 ejercicios prácticos, unas 3 horas de trabajo con dificultad fácil. Practicarás grupos de radio buttons, fieldsets, labels y legends, los tipos de input `email`, `tel` y `url`, los atributos `required` y `autofocus`, un formulario montado con tablas y selectores CSS sin clases ni IDs. Cada paso tiene su vídeo explicativo en español y en inglés. -1. Uso de entradas/inputs de texto, text areas, entradas/inputs de fecha y entradas/inputs numéricas. + +## 📋 Ficha del tutorial + +- **Dificultad**: fácil +- **Duración estimada**: 3 horas +- **Pasos**: 8 carpetas — 1 de bienvenida sin código + 7 ejercicios que escribes tú +- **Tecnologías**: HTML5, CSS, LearnPack, Node.js +- **Vídeos explicativos**: 8 en español y 8 en inglés, uno por paso +- **Soluciones de referencia**: 7 de las 8 carpetas incluyen un `solution.hide.html` o `solution.hide.css` oculto +- **Corrección**: `learn.json` tiene `"disableGrading": true`, así que no hay botón de calificar — comparas con el resultado esperado +- **Editor**: VS Code, en Codespaces, Gitpod o tu propia máquina (editor de LearnPack v5.0) +- **Idiomas**: [Español](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/blob/HEAD/README.es.md) · [English](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/blob/HEAD/README.md) + -2. Uso de dropdowns. +## 🎯 ¿Qué vas a aprender? -3. Validaciones de formulario. +Los formularios son la parte de HTML donde la página deja de ser un documento y se convierte en una interfaz. Este tutorial acota el temario a propósito: las etiquetas y atributos que el navegador ya te da, y el CSS justo para que no queden feos. Al terminar sabrás: -4. Dar estilos a un formulario. +- Escribir un documento HTML completo desde un fichero vacío y en el orden correcto: ``, ``, ``, `` y `<body>`. +- Crear grupos de radio buttons con `<input type="radio">` y entender que lo que hace excluyentes dos opciones es compartir el atributo `name`, no el `value`. +- Estructurar un formulario con semántica real usando `<fieldset>`, `<legend>` y `<label>` en lugar de `<div>` sueltos. +- Usar los tipos de input de HTML5 que activan el teclado móvil adecuado y las comprobaciones del propio navegador: `type="email"`, `type="tel"` y `type="url"`. +- Aplicar los atributos que te dan validación y foco gratis: `required` para impedir el envío con el campo vacío y `autofocus` para colocar el cursor al cargar la página. +- Combinar `<select>` con `<option>`, `<input type="checkbox">` y `<textarea>` dentro de un mismo formulario. +- Dar estilo a un formulario con CSS plano: selectores de atributo como `input[type=submit]`, fieldsets sin borde, inputs de texto reducidos a una línea inferior y un botón de envío de ancho completo. +- Sustituir selectores de clase y de ID por selectores de elemento, de atributo y de pseudoelemento que rindan exactamente igual. +- Leer un mockup y reproducirlo: cuatro ejercicios traen una captura o un GIF del resultado que tienes que clavar, y en el `06` y el `08` esa imagen es prácticamente todo el enunciado. -<!-- hide --> -#### Antes de empezar... hay otros tutoriales +## 👀 ¿Qué vas a construir? -<ol> - <li><a href="https://github.com/4GeeksAcademy/html-tutorial-exercises-course">Aprende HTML</a></li> - <li><a href="https://github.com/4GeeksAcademy/html-forms-tutorial-exercises">Aprende Formularios HTML5</a>← 🔥 Estás aquí</li> - <li><a href="https://github.com/4GeeksAcademy/css-tutorial-exercises-course">Aprende CSS</a></li> - <li><a href="https://github.com/4GeeksAcademy/css-layouts-tutorial-exercises">Aprende CSS Layouts</a></li> - <li><a href="https://github.com/4GeeksAcademy/bootstrap-exercises-tutorial">Aprende Bootstrap</a></li> -</ol> +No hay un proyecto final único. Recorres 8 carpetas dentro de [`exercises/`](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/tree/HEAD/exercises), cada una una página real que ves en vivo: -## Instalación en un clic (recomendado) +1. **`01` Bienvenida** — una introducción con vídeo y sin código. Es el único paso en el que no escribes nada. +2. **`02` Hello World** — partes de un fichero que solo tiene un comentario y escribes el esqueleto completo del documento, con `Hello World` dentro de `<title>` para que aparezca en la pestaña del navegador. +3. **`03` Type Radio** — cuatro inputs de tipo radio dentro de un formulario que ya existe: dos para el sexo y dos para la orientación sexual, agrupados en exactamente dos `name` para que solo se pueda elegir una opción por pregunta. +4. **`04` Fieldsets, labels y estilos** — te dan un formulario de suscripción con tres fieldsets y un `style.css` vacío. Escribes el CSS: la tipografía Lato en el `<body>`, el formulario en `inline-block`, fieldsets sin bordes ni márgenes, labels con `font-weight: 400`, inputs de texto reducidos a una línea negra inferior y un botón SUBSCRIBE rojo `#f65252` a todo lo ancho. +5. **`05` HTML Form** — un formulario existente usa `type="Text"` para todo. Lo cambias por `type="email"`, `type="tel"` y `type="url"`, y añades `required` y `autofocus` al campo de email. La hoja de estilos ya trae reglas para esos tres tipos. +6. **`06` Replicar un formulario simple** — el ejercicio de lienzo en blanco: reconstruyes desde una captura un formulario noventero montado con una tabla, con un input de texto, dos radios, un `<select>`, dos checkboxes, un `<textarea>` y un botón de envío, dándole estilo desde el bloque `<style>` del `<head>`. +7. **`07` Estilos sin ID ni clase** — un formulario de registro multipaso ya terminado, con una barra de progreso hecha con contadores CSS. Reescribes todos los selectores de clase de `style.css` usando selectores de elemento, descendencia y atributo, conservando solo `.active` y sin mover un píxel. +8. **`08` Formulario de login espectacular** — el HTML es intocable y `style.css` está vacío. Solo con CSS conviertes un formulario pelado de usuario y contraseña en una pantalla de login centrada sobre un fondo azul marino. -Puedes empezar estos ejercicios en pocos segundos haciendo clic en: [Abrir en Codespaces](https://codespaces.new/?repo=4GeeksAcademy/html-forms-tutorial-exercises) (recomendado) o [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/html-forms-tutorial-exercises.git). +El ejercicio `06` es el ejemplo más claro del formato: te dan la imagen objetivo y tienes que deducir el marcado que la produce. -> Una vez ya tengas abierto VSCode, los ejercicios de LearnPack deberían empezar automáticamente, si esto no sucede puedes intentar empezar los ejercicios escribiendo este comando en tu terminal: `$ learnpack start` +![Captura objetivo del ejercicio 06: una tabla HTML con bordes y una fila de cabecera lila con las columnas Name y Value, seguida de filas para Name con un campo de texto, Sex con radios Male y Female, Eye color con un desplegable en verde, Check all that apply con dos checkboxes de más de 6 pies de alto y más de 200 libras, y una fila final con un textarea titulado describe your athletic ability y un botón Enter my information](https://raw.githubusercontent.com/4GeeksAcademy/html-forms-tutorial-exercises/master/.learn/assets/5xKY0rI.png) -## Instalación local: +El último ejercicio es CSS puro, y este es el resultado al que apuntas: -Clona el repositorio en tu ambiente local y sigue los siguientes pasos: +![Captura objetivo del ejercicio 08: una pantalla de login sobre fondo azul marino oscuro con la palabra Login en blanco y en grande, un campo de usuario, un campo de contraseña y un botón azul ancho que dice Let me in, todo centrado en una columna estrecha](https://raw.githubusercontent.com/4GeeksAcademy/html-forms-tutorial-exercises/master/.learn/assets/BCp1oWy.png) -1. Instala LearnPack, el package manager para tutoriales de aprendizaje y el HTML compiler plugin para LearnPack, asegúrate también de tener node.js 14+: +## 🎓 ¿Qué necesitas antes de empezar? -```bash -$ npm i @learnpack/learnpack -g -``` +- **Bases de HTML**: sí. El ejercicio `02` te pide el esqueleto del documento sin explicártelo, así que conviene que ya sepas qué es una etiqueta. Si no, empieza por [Aprende lo básico de HTML Interactivamente](https://4geeks.com/es/interactive-exercise/html-exercises-es). +- **CSS**: ayuda, pero no es obligatorio. Cuatro ejercicios son de CSS, y en el `04` y el `05` te dan las reglas exactas, así que puedes aprender la sintaxis sobre la marcha. Si prefieres la teoría antes, el tutorial hermano es [Aprende CSS con Ejercicios Interactivos](https://4geeks.com/es/interactive-exercise/css-exercises-es). +- **JavaScript**: no hace falta en ningún momento. En todo el paquete no se usa JS más allá de los dos ficheros de test. +- **Instalación, la vía fácil**: nada que instalar. Abre el repositorio en GitHub Codespaces o Gitpod y los ejercicios arrancan solos. +- **Instalación, la vía local**: Node.js 14 o superior y el CLI `@learnpack/learnpack` instalado de forma global. +- **Tiempo**: unas 3 horas en total, y LearnPack recuerda por dónde ibas entre sesión y sesión. -2. Descarga estos ejercicios en particular usando LearnPack y luego `cd` para entrar en la carpeta: +## ✅ ¿Cómo sabes si tu formulario está bien? -```bash -$ git clone https://github.com/4GeeksAcademy/html-forms-tutorial-exercises -$ cd html-forms-tutorial-exercises -``` +La corrección automática está desactivada a propósito en este paquete — `learn.json` incluye `"disableGrading": true` — así que no hay botón de aprobado o suspenso. A cambio tienes cuatro formas de comprobarlo: + +- **La vista previa en vivo.** Cada ejercicio renderiza tu `index.html` junto a las instrucciones, así que una etiqueta mal cerrada o un borde que falta se ven al instante. +- **Las imágenes objetivo.** Los ejercicios `04`, `06`, `07` y `08` traen una captura o un GIF del resultado esperado. Tu trabajo es clavarlo. +- **Las soluciones de referencia.** Siete de las ocho carpetas incluyen un `solution.hide.html` o `solution.hide.css` con una respuesta que funciona y que puedes destapar cuando te atasques. +- **Los vídeos.** El README de cada paso enlaza una explicación grabada: 8 en español y 8 en inglés, y cada idioma es una grabación distinta. + +Dos carpetas, `02-hello-world` y `03-Type-Radio`, todavía conservan un `tests.js` escrito con Jest y jsdom. Ya no se ejecutan como calificación, pero merece la pena leerlos porque describen el resultado esperado con precisión milimétrica: el `02` espera que `<!DOCTYPE html>`, `<html`, `<head>`, `<title>` y `<body>` aparezcan en ese orden y que el título sea exactamente `Hello World`; el `03` espera exactamente cuatro elementos `input[type=radio]`, los valores `Masculino`, `Femenino`, `Heterosexual` y `LGTBI` en ese orden (o `Male`, `Female`, `Heterosexual` y `LGBTI` en inglés) y exactamente dos `name` distintos, uno por pareja. + +## 💡 ¿Qué errores conviene evitar? + +- **Ponerle un `name` distinto a cada radio button.** En el ejercicio `03` es el fallo de siempre: con cuatro nombres diferentes puedes marcar las cuatro opciones a la vez, y con un solo nombre compartido entre las dos preguntas solo puedes marcar una de las cuatro. Necesitas dos nombres, uno por pareja. +- **Escribir el doctype en minúsculas.** Las comprobaciones del `02` buscan la cadena literal `<!DOCTYPE html>`, y `<!doctype html>` no coincide. Lo mismo con el título: `Hello World`, con las dos mayúsculas y sin espacios de más. +- **Escribir el CSS en el fichero equivocado.** En los ejercicios `04`, `07` y `08` ya hay un `style.css` enlazado desde `index.html`; que esté vacío en el `04` y en el `08` es lo normal. El `06` es justo al revés: no hay hoja de estilos y el CSS va en el bloque `<style>` que ya está en el `<head>`. +- **Reescribir la hoja de estilos en el ejercicio `05`.** Solo tienes que tocar `index.html`. El CSS ya apunta a `input[type=email]`, `input[type=tel]` e `input[type=url]`, así que la línea inferior sobrevive al cambio sola. Y `required` y `autofocus` van únicamente en el input de email. +- **Cargarte `.active` en el ejercicio `07`.** Es el único selector de clase que puedes conservar y es el que colorea el paso actual de la barra de progreso. Todo lo demás — el contenedor del formulario, el fieldset, los inputs, los títulos, los elementos de la barra — hay que alcanzarlo con selectores de elemento, descendencia, atributo o pseudoelemento, y los contadores CSS de `:before` y `:after` tienen que seguir numerando los pasos. +- **Dar por hecho que `<label for="...">` ya funciona.** Los ficheros de partida usan `for="firstname"` mientras que el input solo tiene `name="firstname"`. El atributo `for` apunta a un `id`, no a un `name`, así que esas etiquetas no están realmente asociadas a su campo. Añade los `id` correspondientes y al hacer clic en la etiqueta se enfocará el input, tal y como lo resuelve la solución de referencia del ejercicio `06`. + +## ❓ Preguntas frecuentes + +### ¿Cómo agrupo radio buttons para que solo se pueda elegir uno? + +Dales a todos los radios de la misma pregunta el mismo atributo `name`. El navegador trata los nombres iguales como un grupo y desmarca los demás cuando eliges uno. El atributo `value` es lo que se envía al servidor y sí debe ser distinto en cada opción. Eso es exactamente lo que se practica en el ejercicio `03`. + +### ¿Cuál es la diferencia entre GET y POST en un formulario HTML? + +`method="get"` añade los valores a la URL como query string: el resultado se puede guardar en marcadores, pero queda a la vista en la barra de direcciones y en el historial. `method="post"` los envía en el cuerpo de la petición, que es lo que se usa para contraseñas o para textos largos. En este repositorio ves los dos: los ejercicios `04` y `05` usan `method="get"`, y el `07` y el `08` usan `method="post"`. + +### ¿Basta con el atributo `required` para validar un formulario? + +Para la experiencia de usuario, sí: impide que el navegador envíe el formulario con el campo vacío y, combinado con `type="email"` o `type="url"`, también comprueba la forma del valor. Para la seguridad, no. La validación del lado del cliente se salta con las herramientas de desarrollo en cuestión de segundos, así que el servidor tiene que volver a validarlo todo. `required` se añade en el ejercicio `05`. + +### ¿Tengo que instalar algo para hacer los ejercicios? + +No. Abriendo el repositorio en GitHub Codespaces o en Gitpod tienes VS Code en el navegador con LearnPack ya funcionando. Instalarlo en local es opcional y solo necesita Node.js 14 o superior más el paquete `@learnpack/learnpack`. + +### ¿Estos ejercicios se corrigen automáticamente? -> Nota: Una vez que termines de descargar, encontrarás una carpeta "exercises" que contiene todos los ejercicios. +En este paquete no. `learn.json` tiene `"disableGrading": true`, así que no hay botón de calificar. Dos de las ocho carpetas todavía conservan ficheros de test de Jest de una versión anterior y puedes leerlos como una especificación exacta, pero el flujo previsto es comparar tu página con la captura objetivo y con la solución de referencia que viene en cada carpeta. -3. Inicializa el tutorial/ejercicios ejecutando el siguiente comando en el mismo nivel donde se encuentra tu archivo learn.json: +### ¿Es gratis y puedo reutilizar el material? -```bash +Acceder no cuesta nada: el repositorio es público y puedes ejecutarlo en Codespaces o en local sin pagar. Otra cosa es la licencia: el material no es de código abierto. [`LICENSE.md`](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/blob/HEAD/LICENSE.md) reserva todos los derechos de propiedad intelectual y prohíbe republicar, revender, redistribuir o copiar el contenido. El HTML y el CSS que escribas en tu copia son tuyos. + +<!-- hide --> +## 📚 Otros tutoriales de esta serie + +1. [Aprende lo básico de HTML Interactivamente](https://4geeks.com/es/interactive-exercise/html-exercises-es) +2. [Aprende cómo usar e interactuar con Formularios en HTML](https://4geeks.com/es/interactive-exercise/forms-exercises-es) — estás aquí +3. [Aprende CSS con Ejercicios Interactivos](https://4geeks.com/es/interactive-exercise/css-exercises-es) +4. [Construye diseños de sitios web con CSS](https://4geeks.com/es/interactive-exercise/css-layouts-tutorial-exercises-es) +5. [Tutorial para Aprender Bootstrap desde Cero](https://4geeks.com/es/interactive-exercise/bootstrap-exercises-es) +6. [Aprende cómo manipular el DOM con JavaScript](https://4geeks.com/es/interactive-exercise/the-dom-exercises-es) + +## 🚀 Cómo empezar + +Lo más rápido es un clic, sin instalar nada: + +- [Abrir en Codespaces](https://github.com/codespaces/new/?repo=4GeeksAcademy/html-forms-tutorial-exercises) (recomendado) +- [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/html-forms-tutorial-exercises.git) + +Cuando se abra VS Code, los ejercicios de LearnPack deberían arrancar solos. Si no lo hacen, escribe esto en la terminal: + +```sh $ learnpack start ``` -<!-- endhide --> -## ¿Cómo están organizados los ejercicios? +También puedes ver el [vídeo de introducción](https://www.youtube.com/watch?v=tCI20Ueo6Q8) antes de empezar. + +## 💻 Instalación local -Cada ejercicio es una pequeña aplicación de React que contiene los siguientes archivos: +1. Instala LearnPack de forma global. Necesitas Node.js 14 o superior: -1. **index.js:** representa el archivo de entrada para toda la aplicación. -2. **README.md:** contiene las instrucciones de los ejercicios. -3. **test.js:** no tienes que abrir este archivo, contiene el script del test para el ejercicio. + ```sh + $ npm i @learnpack/learnpack -g + ``` -> Nota: Los ejercicios son autograduados, pero los tests son muy rígidos y estrictos, mi recomendación es que no prestes demasiada atención a los tests y los uses solo como una sugerencia o podrías frustrarte. +2. Clona el repositorio y entra en la carpeta: -## Colaboradores - -Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + ```sh + $ git clone https://github.com/4GeeksAcademy/html-forms-tutorial-exercises + $ cd html-forms-tutorial-exercises + ``` -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (codificador) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 🤓 (tutorial de compilación) ✅ (documentación) 📖 +3. Arranca el tutorial desde el mismo nivel donde está `learn.json`: -Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! + ```sh + $ learnpack start + ``` -Este y otros ejercicios son usados para [aprender a programar](https://4geeksacademy.com/es/aprender-a-programar/aprender-a-programar-desde-cero) por parte de los alumnos de 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) realizado por [Alejandro Sánchez](https://twitter.com/alesanchezr) y muchos otros contribuyentes. Conoce más sobre nuestros [Cursos de Programación](https://4geeksacademy.com/es/curso-de-programacion-desde-cero?lang=es) para convertirte en [Full Stack Developer](https://4geeksacademy.com/es/coding-bootcamps/desarrollador-full-stack/?lang=es), o nuestro [Data Science Bootcamp](https://4geeksacademy.com/es/coding-bootcamps/curso-datascience-machine-learning). +Tienes más detalle en la [documentación de LearnPack](https://4geeks.com/docs/learnpack/quickstart-for-learners). + +## 📝 Cómo están organizados los ejercicios + +Cada paso es una carpeta dentro de [`exercises/`](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/tree/HEAD/exercises). Según el paso te encontrarás: + +1. **`index.html`** — la página que editas y previsualizas. Está en todas las carpetas menos en `01-welcome`. +2. **`README.md`** — las instrucciones, las pistas y el resultado esperado, con un `README.es.md` al lado para el español. Los dos empiezan con una cabecera YAML que guarda el enlace al vídeo. +3. **`style.css`** — solo en los ejercicios `04`, `05`, `07` y `08`. En el `04` y el `08` está vacío a propósito. +4. **`solution.hide.html`** o **`solution.hide.css`** — la solución de referencia, oculta hasta que la pides. Está en todas las carpetas menos en `01-welcome`. +5. **`tests.js`** — restos de assertions de Jest, solo en `02-hello-world` y `03-Type-Radio`. La corrección está desactivada, así que no se ejecutan. + +## 🤝 Colaboradores + +Gracias a estas personas maravillosas ([leyenda de emojis](https://github.com/kentcdodds/all-contributors#emoji-key)): + +- [Alejandro Sánchez (@alesanchezr)](https://github.com/alesanchezr) — autor de los ejercicios y quien más commits ha hecho en el repositorio, con 104 commits +- [@josemoracard](https://github.com/josemoracard) +- [@tommygonzaleza](https://github.com/tommygonzaleza) +- [@Charlytoc](https://github.com/Charlytoc) +- [@ElviraQDP](https://github.com/ElviraQDP) +- [@Lorenagubaira](https://github.com/Lorenagubaira) + +Puedes ver la [lista completa de colaboradores](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/graphs/contributors): 24 personas han hecho commits en este repositorio. El proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors) y toda contribución es bienvenida. + +Este y muchos otros tutoriales interactivos se construyen y se mantienen en [4Geeks Academy](https://4geeks.com/es). +<!-- endhide --> diff --git a/README.md b/README.md index 23ab27d..8a44cb7 100644 --- a/README.md +++ b/README.md @@ -1,89 +1,193 @@ <!-- hide --> -# HTML5 Forms Tutorial & Exercises -<a href="https://www.4geeksacademy.co"><img height="280" align="right" src="https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/blob/master/.learn/assets/badge.png?raw=true"></a> +<div align="center"> -> By [@alesanchezr](https://twitter.com/alesanchezr) and [other contributors](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/graphs/contributors) at [4Geeks Academy](https://4geeksacademy.co/) +# Learn how to use and interact with HTML Forms -![last commit](https://img.shields.io/github/last-commit/4geeksacademy/html-forms-tutorial-exercises) -[![build by developers](https://img.shields.io/badge/build_by-Developers-blue)](https://breatheco.de) -[![build by developers](https://img.shields.io/twitter/follow/4geeksacademy?style=social&logo=twitter)](https://twitter.com/4geeksacademy) +[![Interactive tutorial](https://img.shields.io/badge/4Geeks-Interactive_tutorial-2563eb?style=for-the-badge)](https://4geeks.com/en/interactive-exercise/forms-exercises) +[![8 exercises with LearnPack](https://img.shields.io/badge/LearnPack-8_exercises-2563eb?style=for-the-badge)](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/tree/HEAD/exercises) +[![Open in Codespaces](https://img.shields.io/badge/Open_in-Codespaces-fb5a1f?style=for-the-badge&logo=github)](https://github.com/codespaces/new/?repo=4GeeksAcademy/html-forms-tutorial-exercises) -> *Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/blob/master/README.es.md) :es:* +![Cover of the tutorial: a sheet of paper with the word HTML5 in dark grey above the word FORMS in orange, the subtitle Interactive Tutorial, a small icon of a form with input boxes, and a black footer band reading time to code](https://raw.githubusercontent.com/4GeeksAcademy/html-forms-tutorial-exercises/master/.learn/assets/preview.png) +</div> <!-- endhide --> -Forms are so important in the world of HTML, CSS and Javascript that I decided to give them a special course to focus in all the inputs, buttons and elements that HTML brings by default to focus on interaction. During these exercises you will learn the following: +This LearnPack tutorial covers HTML5 forms in 8 steps: an intro video plus 7 hands-on exercises, about 3 hours of work at an easy difficulty level. You practise radio groups, fieldsets, labels and legends, the HTML5 input types `email`, `tel` and `url`, the `required` and `autofocus` attributes, a table-based form, and CSS selectors that use no classes or IDs. Every step has a video walkthrough in English and Spanish. -1. How to use text inputs, text areas, date inputs and numeric inputs. +<!-- hide --> +## 📋 About this tutorial + +- **Difficulty**: easy +- **Estimated duration**: 3 hours +- **Steps**: 8 folders — 1 welcome step with no code + 7 exercises you write +- **Technologies**: HTML5, CSS, LearnPack, Node.js +- **Video walkthroughs**: 8 in English and 8 in Spanish, one per step +- **Reference solutions**: 7 of the 8 folders ship a hidden `solution.hide.html` or `solution.hide.css` +- **Grading**: `learn.json` sets `"disableGrading": true`, so there is no grade button — you compare against the expected result +- **Editor**: VS Code, in Codespaces, Gitpod or your own machine (LearnPack editor v5.0) +- **Languages**: [English](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/blob/HEAD/README.md) · [Español](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/blob/HEAD/README.es.md) +<!-- endhide --> -2. How to use dropdowns. +## 🎯 What will you learn? -3. How to form preventive validations. +Forms are the part of HTML where the page stops being a document and starts being an interface. This tutorial keeps the scope narrow on purpose: the tags and attributes the browser already gives you, and the CSS needed to make them look decent. By the end you will be able to: -4. The difference between GET and POST. +- Write a complete HTML document from an empty file, in the right order: `<!DOCTYPE html>`, `<html>`, `<head>`, `<title>` and `<body>`. +- Build radio button groups with `<input type="radio">`, and understand why the shared `name` attribute — not the `value` — is what makes two options mutually exclusive. +- Structure a form semantically with `<fieldset>`, `<legend>` and `<label>` instead of loose `<div>` tags. +- Use the HTML5 input types that trigger the right mobile keyboard and the browser's own checks: `type="email"`, `type="tel"` and `type="url"`. +- Apply the attributes that give you validation and focus for free: `required` to block submission of an empty field, and `autofocus` to place the cursor on load. +- Combine `<select>` with `<option>`, `<input type="checkbox">` and `<textarea>` inside a single form. +- Style a form with plain CSS: attribute selectors like `input[type=submit]`, borderless fieldsets, a bottom-border-only text input, and a full-width coloured submit button. +- Replace class and ID selectors with element, attribute and pseudo-element selectors that produce exactly the same rendering. +- Read a mockup and reproduce it — four of the exercises hand you a target screenshot or GIF to match, and in `06` and `08` that image is practically the whole brief. -5. Styling a form. +## 👀 What will you build? -<!-- hide --> -#### Before we start... other related tutorials +There is no single final project. You work through 8 folders inside [`exercises/`](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/tree/HEAD/exercises), each one a real page you open in a live preview: -<ol> - <li><a href="https://github.com/4GeeksAcademy/html-tutorial-exercises-course">Learn HTML</a></li> - <li><a href="https://github.com/4GeeksAcademy/html-forms-tutorial-exercises">Learn HTML5 Forms</a>← 🔥 You are here now</li> - <li><a href="https://github.com/4GeeksAcademy/css-tutorial-exercises-course">Learn CSS</a></li> - <li><a href="https://github.com/4GeeksAcademy/css-layouts-tutorial-exercises">Learn CSS Layouts</a></li> - <li><a href="https://github.com/4GeeksAcademy/bootstrap-exercises-tutorial">Learn Bootstrap</a></li> -</ol> +1. **`01` Welcome** — an introduction with a video and no code. This is the only step where you write nothing. +2. **`02` Hello World** — you start from a file containing a single comment and write the whole document skeleton, with `Hello World` inside `<title>` so it shows in the browser tab. +3. **`03` Type Radio** — four radio inputs inside a form that is already there: two for sex and two for sexual orientation, grouped into exactly two `name` groups so only one option per question can be picked. +4. **`04` Fieldsets, labels and styles** — a subscribe form with three fieldsets is given to you and `style.css` is empty. You write the CSS: the Lato font on `<body>`, an `inline-block` form, fieldsets without borders or margins, labels at `font-weight: 400`, text inputs reduced to a single black bottom border, and a full-width red `#f65252` SUBSCRIBE button. +5. **`05` HTML Form** — an existing form uses `type="Text"` for everything. You swap in `type="email"`, `type="tel"` and `type="url"`, then add `required` and `autofocus` to the email field. The stylesheet already has rules for those three types. +6. **`06` Replicate Simple Form** — the empty-canvas exercise: rebuild a 1990s-style table form from a screenshot, with a text input, a pair of radios, a `<select>`, two checkboxes, a `<textarea>` and a submit button, styling it from the `<style>` block in the `<head>`. +7. **`07` Style without ID or Class** — a finished multi-step signup form with a CSS-counter progress bar. Rewrite every class selector in `style.css` using element, descendant and attribute selectors instead, keeping only `.active`, without changing a single pixel. +8. **`08` Spectacular login form** — the HTML is off limits and `style.css` is empty. Using CSS alone, turn a bare username/password form into a centred login screen on a dark navy background. -## One click installation (recommended): +Exercise `06` is the clearest example of the format: you get the target image and have to work out the markup that produces it. -You can open these exercises in just a few seconds by clicking: [Open in Codespaces](https://codespaces.new/?repo=4GeeksAcademy/html-forms-tutorial-exercises) (recommended) or [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/html-forms-tutorial-exercises.git). +![Target screenshot for exercise 06: a bordered HTML table with a lavender header row of Name and Value columns, followed by rows for Name with a text field, Sex with Male and Female radio buttons, Eye color with a green dropdown, Check all that apply with two checkboxes for over 6 feet tall and over 200 pounds, and a final row with a textarea labelled describe your athletic ability and an Enter my information button](https://raw.githubusercontent.com/4GeeksAcademy/html-forms-tutorial-exercises/master/.learn/assets/5xKY0rI.png) -> Once you have VSCode open the LearnPack exercises should start automatically. If exercises don't run automatically you can try typing on your terminal: `$ learnpack start` +The last exercise is pure CSS, and this is the result you are aiming for: -## Local installation +![Target screenshot for exercise 08: a login screen on a dark navy background with the word Login in large white bold type, a username field, a password field and a wide blue button labelled Let me in, all centred in a narrow column](https://raw.githubusercontent.com/4GeeksAcademy/html-forms-tutorial-exercises/master/.learn/assets/BCp1oWy.png) -Clone the repository in your local environment and follow the steps below: +## 🎓 What do you need before starting? -1. Install LearnPack, the package manager for learning tutorials and the HTML compiler plugin for LearnPack, make sure you also have node.js 14+: +- **HTML basics**: yes. Exercise `02` asks for the document skeleton with no explanation, so you should already know what a tag is. If you don't, do [Learn the basics of HTML Interactively](https://4geeks.com/en/interactive-exercise/html-exercises) first. +- **CSS**: helpful but not mandatory. Four exercises are CSS work, and exercises `04` and `05` hand you the exact rules to copy, so you can learn the syntax as you go. If you want the theory first, [Learn CSS with Interactive Exercises](https://4geeks.com/en/interactive-exercise/css-exercises) is the companion tutorial. +- **JavaScript**: not needed anywhere. Nothing in this package uses JS beyond the two test files. +- **Setup, easiest path**: nothing to install. Open the repository in GitHub Codespaces or Gitpod and the exercises launch on their own. +- **Setup, local path**: Node.js 14 or higher and the `@learnpack/learnpack` CLI installed globally. +- **Time**: about 3 hours in total, and LearnPack remembers where you left off between sessions. -```bash -$ npm i @learnpack/learnpack -g -``` +## ✅ How do you know your form is correct? -2. Download these particular exercises using LearnPack and `cd` into the folder: +Grading is deliberately switched off in this package — `learn.json` contains `"disableGrading": true` — so there is no pass/fail button. You get four other feedback loops instead: -```bash -$ git clone https://github.com/4GeeksAcademy/html-forms-tutorial-exercises -$ cd html-forms-tutorial-exercises -``` +- **The live preview.** Every exercise renders your `index.html` next to the instructions, so a broken tag or a missing border is visible immediately. +- **Target images.** Exercises `04`, `06`, `07` and `08` come with a screenshot or an animated GIF of the expected result. Your job is to match it. +- **Reference solutions.** Seven of the eight folders ship a `solution.hide.html` or `solution.hide.css` with a working answer you can reveal when you are stuck. +- **Video walkthroughs.** Each step's README links a recorded walkthrough — 8 in English and 8 in Spanish, each language a separate recording. + +Two folders, `02-hello-world` and `03-Type-Radio`, still contain a `tests.js` written with Jest and jsdom. They no longer run as grading, but they are worth reading because they spell out the expected result precisely: exercise `02` wants `<!DOCTYPE html>`, `<html`, `<head>`, `<title>` and `<body>` to appear in that order and the title text to be exactly `Hello World`; exercise `03` wants exactly four `input[type=radio]` elements, the values `Male`, `Female`, `Heterosexual` and `LGBTI` in that order (or `Masculino`, `Femenino`, `Heterosexual` and `LGTBI` in Spanish), and exactly two distinct `name` values, one per pair. + +## 💡 What mistakes should you avoid? + +- **Giving every radio button its own `name`.** In exercise `03` this is the classic failure: with four different names you can tick all four boxes at once, and with a single shared name across both questions you can only ever tick one of the four. You need two names, one per pair. +- **Typing the doctype in lowercase.** The `02` checks look for the literal string `<!DOCTYPE html>`, and `<!doctype html>` does not match it. Same for the title: `Hello World`, with both capitals and no extra spaces. +- **Writing CSS in the wrong file.** In exercises `04`, `07` and `08` there is a `style.css` already linked from `index.html` — the file is empty in `04` and `08`, which is normal. Exercise `06` is the opposite: there is no stylesheet, and the CSS belongs in the `<style>` block already sitting in the `<head>`. +- **Rewriting the stylesheet in exercise `05`.** You only need to change `index.html`. The CSS already targets `input[type=email]`, `input[type=tel]` and `input[type=url]`, so the underlined look survives the swap on its own. And `required` and `autofocus` go on the email input only. +- **Losing `.active` in exercise `07`.** It is the one class selector you are allowed to keep, and it is what colours the current step of the progress bar. Everything else — the form wrapper, the fieldset, the inputs, the headings, the progress bar items — has to be reached through element, descendant, attribute or pseudo-element selectors, and the `:before`/`:after` CSS counters must keep numbering the steps. +- **Assuming `<label for="...">` already works.** The starter files use `for="firstname"` while the input only has `name="firstname"`. `for` points at an `id`, not a `name`, so those labels are not actually bound to their inputs. Add matching `id` attributes and clicking the label will focus the field — the way the reference solution for exercise `06` does it. + +## ❓ Frequently asked questions + +### How do I group radio buttons so only one can be selected? + +Give every radio in the same question the same `name` attribute. The browser treats matching names as one group and deselects the others when you pick one. The `value` attribute is what gets sent to the server, and it must be different for each option. This is exactly what exercise `03` drills. + +### What is the difference between GET and POST in an HTML form? + +`method="get"` appends the field values to the URL as a query string, which makes the result bookmarkable but visible in the address bar and browser history. `method="post"` sends them in the request body instead, which is what you use for passwords or anything long. In this repository you can see both: exercises `04` and `05` use `method="get"`, and `07` and `08` use `method="post"`. + +### Is the `required` attribute enough to validate a form? + +For the user experience, yes — it stops the browser from submitting while the field is empty, and combined with `type="email"` or `type="url"` it also checks the shape of the value. For security, no. Client-side validation can be bypassed with the browser devtools in seconds, so the server has to validate everything again. Exercise `05` is where you add `required`. + +### Do I need to install anything to do these exercises? + +No. Opening the repository in GitHub Codespaces or Gitpod gives you VS Code in the browser with LearnPack already running. Installing locally is optional and only needs Node.js 14 or higher plus the `@learnpack/learnpack` package. + +### Are these exercises graded automatically? -> Note: Once you finish downloading, you will find an "exercises" folder that contains all the exercises within. +Not in this package. `learn.json` sets `"disableGrading": true`, so there is no grade button. Two of the eight folders still carry Jest test files from an earlier version, and you can read them as a precise spec, but the intended workflow is comparing your page with the target screenshot and with the reference solution included in each folder. -3. Start the tutorial/exercises by running the following command at the same level where your learn.json file is: +### Is this tutorial free, and can I reuse the material? -```bash +Access costs nothing: the repository is public and you can run it in Codespaces or locally at no charge. The material is not open source, though. [`LICENSE.md`](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/blob/HEAD/LICENSE.md) reserves all intellectual property rights and forbids republishing, reselling, redistributing or copying the content. The HTML and CSS you write in your own copy is yours. + +<!-- hide --> +## 📚 Other tutorials in this series + +1. [Learn the basics of HTML Interactively](https://4geeks.com/en/interactive-exercise/html-exercises) +2. [Learn how to use and interact with HTML Forms](https://4geeks.com/en/interactive-exercise/forms-exercises) — you are here +3. [Learn CSS with Interactive Exercises](https://4geeks.com/en/interactive-exercise/css-exercises) +4. [Build Website Layouts with CSS](https://4geeks.com/en/interactive-exercise/css-layouts-tutorial-exercises) +5. [Learn Bootstrap from Zero](https://4geeks.com/en/interactive-exercise/bootstrap-exercises) +6. [Learn how to manipulate The DOM with JS](https://4geeks.com/en/interactive-exercise/the-dom-exercises) + +## 🚀 How to start + +The fastest way is one click, with nothing to install: + +- [Open in Codespaces](https://github.com/codespaces/new/?repo=4GeeksAcademy/html-forms-tutorial-exercises) (recommended) +- [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/html-forms-tutorial-exercises.git) + +Once VS Code opens, the LearnPack exercises should start on their own. If they don't, type this in the terminal: + +```sh $ learnpack start ``` -<!-- endhide --> -## How are the exercises organized? +You can also watch the [intro video](https://www.youtube.com/watch?v=83HxtkBq7Yc) before you begin. -Each exercise is a small React application containing the following files: +## 💻 Local installation -1. **index.html:** represents the entry file for the entire exercise. -2. **README.md:** contains exercise instructions. -3. **test.js:** you don't have to open this file, it contains the testing script for the exercise. +1. Install LearnPack globally. You need Node.js 14 or higher: -> Note: The exercises have automatic grading, but it's very rigid and strict, my recommendation is to not take the tests too serious and use them only as a suggestion, or you may get frustrated. + ```sh + $ npm i @learnpack/learnpack -g + ``` -## Contributors +2. Clone the repository and enter the folder: -Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + ```sh + $ git clone https://github.com/4GeeksAcademy/html-forms-tutorial-exercises + $ cd html-forms-tutorial-exercises + ``` -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 🤓 -(build-tutorial) ✅ (documentation) 📖 +3. Start the tutorial from the same level where `learn.json` lives: -This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! + ```sh + $ learnpack start + ``` -This and many other exercises are built by students as part of the 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) by [Alejandro Sánchez](https://twitter.com/alesanchezr) and many other contributors. Find out more about our [Full Stack Developer Course](https://4geeksacademy.com/us/coding-bootcamps/part-time-full-stack-developer), and [Data Science Bootcamp](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning). +More detail in the [LearnPack documentation](https://4geeks.com/docs/learnpack/quickstart-for-learners). + +## 📝 How the exercises are organized + +Every step is a folder inside [`exercises/`](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/tree/HEAD/exercises). Depending on the step you will find: + +1. **`index.html`** — the page you edit and preview. Present in all folders except `01-welcome`. +2. **`README.md`** — the instructions, hints and expected result, with a `README.es.md` next to it for Spanish. Both start with a YAML header holding the video link. +3. **`style.css`** — only in exercises `04`, `05`, `07` and `08`. It is empty on purpose in `04` and `08`. +4. **`solution.hide.html`** or **`solution.hide.css`** — the reference solution, hidden until you ask for it. Present in all folders except `01-welcome`. +5. **`tests.js`** — leftover Jest assertions, only in `02-hello-world` and `03-Type-Radio`. Grading is disabled, so they do not run. + +## 🤝 Contributors + +Thanks to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + +- [Alejandro Sánchez (@alesanchezr)](https://github.com/alesanchezr) — author of the exercises and the most active committer in the repository, with 104 commits +- [@josemoracard](https://github.com/josemoracard) +- [@tommygonzaleza](https://github.com/tommygonzaleza) +- [@Charlytoc](https://github.com/Charlytoc) +- [@ElviraQDP](https://github.com/ElviraQDP) +- [@Lorenagubaira](https://github.com/Lorenagubaira) + +See the [full contributor list](https://github.com/4GeeksAcademy/html-forms-tutorial-exercises/graphs/contributors) — 24 people have committed to this repository. This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification and contributions of any kind are welcome. + +This and many other interactive tutorials are built and maintained at [4Geeks Academy](https://4geeks.com). +<!-- endhide -->