Tengo un formulario simple con 2 entradas de texto, 1 número y 1 radio, y estoy tratando de tomar esos datos en mi javascript para crear una matriz de objetos creados con un constructor, pero en el momento presiono el botón de enviar y consola log the array aparece vacío, supongo que por la recarga de la página, pero no estoy seguro.
Aquí está mi código javascript:
let myLibrary = []; //the array I wantd to fill with the objects const form = document.querySelector('#form'); //the form itself // the constructor function Book (title, author, pages, read) { this.title = title; this.author = author; this.pages = pages; this.read = read; } // the submit listener, which takes the data of the form and sends it as argument of the function that pushes the new object to the array form.addEventListener('submit', (e) => { const data = Object.fromEntries(new FormData(e.target).entries()); addBookToLibrary(data); }); function addBookToLibrary (data) { myLibrary.push(new Book(data.title, data.author, data.pages, data.read)); }
He intentado aplicar el método preventDefault() al botón de envío, pero eso detiene el envío del formulario. También intenté hacerlo con FormData() pero tuve el mismo problema.
Lo que hice:
let myLibrary = []; const data = document.querySelector('#form').elements; // HTMLFormElement.elements const btnSubmit = document.querySelector('#btnSubmit'); // Button type button function Book (title, author, pages, read) { this.title = title; this.author = author; this.pages = pages; this.read = read; } // Take the "value" of each element of the form and create a new Book object function addBookToLibrary (data) { myLibrary.push(new Book(data[0].value, data[1].value, data[2].value, data[3].value)); console.log(myLibrary); } // The listener that calls the function btnSubmit.addEventListener('click', () => { addBookToLibrary(data); });