I have a form that I create dynamically. I then 'push' the values entered by the user into an empty array. The problem I have with the preventDefault is that after the first data is entered, when I want to enter new data after clicking the submit button, the preventDefault no longer works and the page is restarted. I pass the code below.
``` const estudiantes = [];
class Estudiante {
constructor(nombre, subject, email) {
this.nombre = nombre;
this.subject = subject;
this.email = email;
}
}
let actividad3 = document.getElementById('actividad-3');
let form = document.createElement('form');
form.innerHTML = `<input type="text" placeholder="Ingrese nombre">
<input type="text" placeholder="Ingrese asignatura">
<input type="email" placeholder="Ingrese una cuenta de correo válida">
<input type="submit" id="btn-submit" value="Enviar Datos">`;
console.log(form);
document.body.append(form);
form.onsubmit = (e) => {
e.preventDefault();
let inputs = e.target.children;
estudiantes.push(new Estudiante(inputs[0].value, inputs[1].value, inputs[2].value));
document.body.innerHTML += '<p>Formulario enviado correctamente</p>'
console.log(estudiantes)
}```
The problem you have is mixing the
append
node function with the HTML content mapping usinginnerHTML
.As they say in this SO answer in English (translated):
If you don't want erratic and unpredictable behavior like the one you're having now, either do it all with nodes using createElement and appendChild for each input, or innerHTML everything, including the form, over a previous existing element.