<!DOCTYPE html>
<html>
<head>
<title>Formulario con jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>
.container {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 50px;
}
.form-group {
margin-bottom: 10px;
}
.form-group label {
display: block;
font-weight: bold;
}
.form-group input {
width: 200px;
padding: 5px;
}
.submit-btn {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<div id="myForm" class="container">
<!-- Formulario generado dinámicamente -->
</div>
<script>
class Formulario {
constructor() {
this.formulario = document.createElement("form");
this.formulario.className = "container";
this.campos = [];
this.crearCampo("nombre", "Nombre");
this.crearCampo("apellido", "Apellido");
this.crearCampo("email", "Email");
this.crearCampo("telefono", "Teléfono");
this.botonEnviar = document.createElement("button");
this.botonEnviar.innerText = "Enviar";
this.botonEnviar.className = "submit-btn";
this.botonEnviar.addEventListener("click", this.enviarFormulario.bind(this));
this.formulario.appendChild(this.botonEnviar);
document.body.appendChild(this.formulario);
}
crearCampo(nombre, etiqueta) {
const formGroup = document.createElement("div");
formGroup.className = "form-group";
const label = document.createElement("label");
label.innerText = etiqueta;
formGroup.appendChild(label);
const input = document.createElement("input");
input.type = "text";
input.name = nombre;
formGroup.appendChild(input);
this.campos.push(input);
this.formulario.appendChild(formGroup);
}
enviarFormulario() {
const datos = {};
for (const campo of this.campos) {
datos[campo.name] = campo.value;
}
console.log(datos);
}
}
$(document).ready(function() {
const formulario = new Formulario();
});
</script>
</body>
</html>
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter