I'm creating a library app where users input data into a form and the values they enter are displayed in its own div.
I have this array
let myLibrary = [
{
title: "The Once and Future King",
author: "White",
pages: 654,
},
{
title: "The Hobbit",
author: "Tolkien",
pages: 304,
},
];
which is automatically displaying each object (for testing purposes) on my page thanks to this forEach()
myLibrary.forEach((book) => {
const bookContent = document.getElementById("content");
const addBook = document.createElement("div");
addBook.className = "book";
bookContent.appendChild(addBook);
addBook.innerHTML = `
<div class="title">
<p class="bookTitle">
<span>${book.title}</span>
</p>
</div>
<div class="body">
<p>
Author: <span>${book.author}</span>
</p>
<p>
Pages: <span>${book.pages}</span>
</p>
</div>`;
});
The forEach makes it so every object inside my array is displayed in its own 280x365 pixel div and the book title, author and page count is displayed in it's own p element. I'm also using flex for organization.
I also have a form which users can input a new book title, author and page number to add to their growing book collection.
const form = document.getElementById("form");
form.addEventListener("submit", updateLibrary);
function updateLibrary(event) {
event.preventDefault();
const title = document.getElementById("title").value;
const author = document.getElementById("author").value;
const pages = document.getElementById("pages").value;
const book = {
title: title,
author: author,
pages: parseInt(pages),
};
myLibrary.push(book);
console.log(myLibrary);
}
When I fill the form out, everything appears to work perfectly. I have console.log in my updateLibrary function and I notice the object is being pushed into the array like I want it to. But every time I hit the submit button, a new div isn't being created for the new book. I'm guessing this has to do with my forEach not triggering the new object but I can't find a way to fix this.
How can I better write my code so a new div is also being created with the new object every time I submit the form?
What I've tried
I've tried rearranging my code so the forEach is below the array, so the updateLibrary function is above and below the forEach.
I've also tried putting the forEach inside the updateLibrary function. That did make it work but it gave me an even worse bug.