Volver
Ctrl+Space
◑
Copiar
Descargar
Restaurar
Ejecutar
Ctrl+Enter
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <title>Eventos en JS — Ejemplo 2</title> <style> body { font-family: Arial, sans-serif; padding: 20px; background: #fff; max-width: 620px; } h3 { margin: 22px 0 8px; font-size: 15px; color: #333; } label { display: block; font-size: 12px; font-weight: bold; color: #555; margin-bottom: 4px; text-transform: uppercase; letter-spacing: 0.5px; } input, select, textarea { width: 100%; padding: 9px 12px; border: 2px solid #ddd; border-radius: 6px; font-size: 14px; box-sizing: border-box; outline: none; transition: border-color 0.2s; } input:focus, select:focus, textarea:focus { border-color: #F7DF1E; } .campo { margin-bottom: 14px; } .hint { font-size: 12px; color: #888; margin-top: 3px; } .ok { color: #059669; font-size: 12px; margin-top: 3px; font-weight: bold; } .err { color: #dc2626; font-size: 12px; margin-top: 3px; font-weight: bold; } .contador { font-size: 12px; color: #888; text-align: right; margin-top: 2px; } .contador.warn { color: #d97706; } .contador.over { color: #dc2626; } button { padding: 10px 24px; background: #F7DF1E; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; font-size: 14px; } button:hover { background: #e6cc00; } .resultado { background: #f0fdf4; border: 1px solid #86efac; border-radius: 6px; padding: 14px; margin-top: 16px; font-size: 14px; display: none; } .log { background: #f9f9f9; border: 1px solid #eee; border-radius: 6px; padding: 8px 12px; font-family: monospace; font-size: 12px; max-height: 100px; overflow-y: auto; margin-top: 6px; } .log div { padding: 1px 0; } </style> </head> <body> <h2>Eventos — Formulario interactivo</h2> <h3>Eventos en tiempo real</h3> <div class="campo"> <label for="nombre">Nombre completo</label> <input type="text" id="nombre" placeholder="Escribí tu nombre..." maxlength="50"> <div class="hint" id="hint-nombre">Mínimo 2 caracteres</div> <div class="log" id="log-nombre"></div> </div> <div class="campo"> <label for="email">Email</label> <input type="text" id="email" placeholder="usuario@ejemplo.com"> <div class="hint" id="hint-email">Verificamos al salir del campo (blur)</div> </div> <div class="campo"> <label for="edad">Edad</label> <input type="number" id="edad" placeholder="Ej: 25" min="13" max="120"> <div class="hint" id="hint-edad"> </div> </div> <div class="campo"> <label for="rol">Rol</label> <select id="rol"> <option value="">— Elegí un rol —</option> <option value="alumno">Alumno</option> <option value="docente">Docente</option> <option value="admin">Administrador</option> </select> <div class="hint" id="hint-rol"> </div> </div> <div class="campo"> <label for="bio">Descripción breve</label> <textarea id="bio" rows="3" maxlength="200" placeholder="Contanos algo sobre vos..."></textarea> <div class="contador" id="contador-bio">0 / 200</div> </div> <button id="btnEnviar">Enviar formulario</button> <div class="resultado" id="resultado"></div> <script> // Eventos en JavaScript - Ejemplo 2: Eventos de formulario const $ = id => document.getElementById(id); // ── Nombre — evento input (en tiempo real) ──────────────────────────── $("nombre").addEventListener("focus", () => { $("hint-nombre").textContent = "📝 Campo activo — escribí tu nombre"; $("hint-nombre").className = "hint"; }); $("nombre").addEventListener("input", (e) => { const val = e.target.value.trim(); const logDiv = $("log-nombre"); const linea = document.createElement("div"); linea.textContent = `input → "${e.target.value}" (${e.target.value.length} chars)`; logDiv.insertBefore(linea, logDiv.firstChild); if (logDiv.children.length > 4) logDiv.lastChild.remove(); if (val.length === 0) { $("hint-nombre").textContent = "Mínimo 2 caracteres"; $("hint-nombre").className = "hint"; } else if (val.length < 2) { $("hint-nombre").textContent = "✗ Muy corto"; $("hint-nombre").className = "err"; } else { $("hint-nombre").textContent = `✓ Nombre: "${val}"`; $("hint-nombre").className = "ok"; } }); $("nombre").addEventListener("blur", () => { const val = $("nombre").value.trim(); if (val.length > 0 && val.length < 2) { $("hint-nombre").textContent = "✗ El nombre debe tener al menos 2 caracteres"; $("hint-nombre").className = "err"; } }); // ── Email — evento blur (al salir del campo) ────────────────────────── $("email").addEventListener("blur", (e) => { const val = e.target.value.trim(); const hint = $("hint-email"); if (!val) { hint.textContent = "Verificamos al salir del campo (blur)"; hint.className = "hint"; return; } const valido = val.includes("@") && val.includes(".") && val.length >= 5; hint.textContent = valido ? `✓ Email válido` : "✗ El email no parece válido"; hint.className = valido ? "ok" : "err"; }); $("email").addEventListener("focus", (e) => { $("hint-email").textContent = "📝 Ingresá tu email"; $("hint-email").className = "hint"; }); // ── Edad — evento input con validación numérica ─────────────────────── $("edad").addEventListener("input", (e) => { const val = parseInt(e.target.value); const hint = $("hint-edad"); if (isNaN(val)) { hint.textContent = " "; hint.className = "hint"; } else if (val < 13) { hint.textContent = "✗ Edad mínima: 13 años"; hint.className = "err"; } else if (val > 120) { hint.textContent = "✗ Edad máxima: 120 años"; hint.className = "err"; } else { hint.textContent = `✓ Edad válida`; hint.className = "ok"; } }); // ── Rol — evento change ─────────────────────────────────────────────── $("rol").addEventListener("change", (e) => { const hint = $("hint-rol"); const mensajes = { alumno: "✓ Acceso básico a tutoriales y ejercicios", docente: "✓ Acceso para crear tutoriales y ejercicios", admin: "✓ Acceso completo al sistema", }; hint.textContent = e.target.value ? mensajes[e.target.value] || "✓ Rol seleccionado" : " "; hint.className = e.target.value ? "ok" : "hint"; }); // ── Bio — contador de caracteres ────────────────────────────────────── $("bio").addEventListener("input", (e) => { const n = e.target.value.length; const max = parseInt(e.target.getAttribute("maxlength")); const cnt = $("contador-bio"); cnt.textContent = `${n} / ${max}`; cnt.className = n >= max ? "contador over" : n >= max * 0.85 ? "contador warn" : "contador"; }); // ── Submit — prevenir recarga y validar ─────────────────────────────── $("btnEnviar").addEventListener("click", (e) => { const nombre = $("nombre").value.trim(); const email = $("email").value.trim(); const edad = parseInt($("edad").value); const rol = $("rol").value; const errores = []; if (nombre.length < 2) errores.push("Nombre inválido"); if (!email.includes("@")) errores.push("Email inválido"); if (isNaN(edad) || edad < 13) errores.push("Edad inválida"); if (!rol) errores.push("Seleccioná un rol"); const resultado = $("resultado"); if (errores.length > 0) { resultado.style.background = "#fef2f2"; resultado.style.border = "1px solid #fca5a5"; resultado.innerHTML = `<strong style="color:#dc2626">✗ ${errores.length} error/es:</strong><br>` + errores.map(e => `• ${e}`).join("<br>"); } else { resultado.style.background = "#f0fdf4"; resultado.style.border = "1px solid #86efac"; resultado.innerHTML = `<strong style="color:#059669">✓ Formulario válido</strong><br><br>` + `<strong>Nombre:</strong> ${nombre}<br>` + `<strong>Email:</strong> ${email}<br>` + `<strong>Edad:</strong> ${edad}<br>` + `<strong>Rol:</strong> ${rol}<br>` + ($("bio").value ? `<strong>Bio:</strong> ${$("bio").value}` : ""); } resultado.style.display = "block"; }); </script> </body> </html>