I have a simple form with 2 text, 1 number and 1 radio inputs, and I'm trying to take that data into my javascript to create an array of objects created with a constructor, but in the moment I hit the submit button and console log the array it appears empty, I suppose because of the reloading of the page, but I'm not sure.
Here is my javascript code:
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));
}
I've tried applying the preventDefault() method to the submit button but that stop the submitting of the form. I also tried doing it with FormData() but I had the same issue.
What I did:
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);
});