I am building a library app that stores user books. It should take user input, store it into an array and then display it on the page. If I manually enter a few object instances in the array, the displayed values are as they should be (eg.title: harry potter, author: JK Rowling, etc), but my object instances created from user input are displayed like so:
function() { return this.title + " by " + this.author + ", " + this.pages + " pages, " + this.read + "."; }
Also, only one instance of object is created even though I've set an event listener on the button. What am I doing wrong?
document.addEventListener("DOMContentLoaded", () => {
document.getElementById('submit').addEventListener("click", addBookToLibrary);
})
let myLibrary = [];
function Book(title,author,pages,read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
this.info = function() {
return this.title + " by " + this.author + ", " + this.pages + " pages, " + this.read + ".";
}
}
function addBookToLibrary() {
let newBook = new Book();
newBook.title = document.getElementById("title").value;
newBook.author = document.getElementById("author").value;
newBook.pages = document.getElementById("pages").value;
newBook.read = document.getElementById("read").value;
myLibrary.push(newBook);
document.querySelector("form").reset(); // clear the form for the next entries
}
addBookToLibrary();
//loop through an array and display each book
function displayBooks() {
for (let i=0; i<myLibrary.length; i++) {
const booksDisplay = document.getElementById("books-display");
const cardBook = document.createElement('div');
cardBook.classList.add("grid-item");
cardBook.innerHTML += Object.values(myLibrary[i]).join(" ");
booksDisplay.appendChild(cardBook);
}
}
displayBooks();
<body>
<header>
</header>
<main>
<div id="page-wrapper">
<form id="new-book">
<label for="title">Title</label><br>
<input type="text" id="title" value=""/><br><br>
<label for="author">Author</label><br>
<input type="text" id="author" value=""/><br><br>
<label for="pages">Pages</label><br>
<input type="text" id="pages" value=""/><br><br>
<label for="read">Read</label><br>
<input type="checkbox" id="read" value=""/><br><br>
<button id="submit">Click to add</button>
</form> <br><br>
<div id="books-display"></div>
</div>
</main>
</body>
Object.values()but.infois a function, so you'd have to call it first. However it already contains all the information, so just docardBook.innerHTML += myLibrary[i].info();You're also calling your functions after declaring them but that's nonsense.addBookToLibraryis already called when the submit button is clicked, and the call todisplayBooksis supposed to go into youraddBookToLibraryfunction, after pushing the new book into the array.