I am trying to store book name value in local storage when the form is submitted in the form of an array. But bookName variable works, but it changes every time a new book name is entered as the function runs again.
let bookName = document.getElementById("bookName").value;
So i want to store all the book names in the form of an array and i get the following error. Here is code:
let libraryForm = document.getElementById("bookForm");
libraryForm.addEventListener("submit", libraryBooksDetails);
function libraryBooksDetails(e) {
e.preventDefault();
console.log("The book details have been submitted");
let bookName = document.getElementById("bookName").value;
let bookAuthor = document.getElementById("author").value;
let bookType;
let fiction = document.getElementById("Fiction");
let programming = document.getElementById("ComputerProgramming");
let personal = document.getElementById("PersonalDevelopement");
if(fiction.checked){
bookType = fiction.value;
}
else if(programming.checked){
bookType = programming.value;
}
else if(personal.checked){
bookType = personal.value;
}
let book = new bookDetails(bookName,bookAuthor,bookType);
let bookData;
bookData = bookData || [];
let nameOfBooks = bookData.push(book.bookName);
localStorage.setItem("books",JSON.stringify(nameOfBooks))
console.log(book);
let display = new Display()
display.add(book);
display.clear();
}
The function I used to store value returns 1. Don't know why?
Any help would be really appreciated.
push, which is the new length of the array (a number), not the array. If you want to storebookData, use that withJSON.stringify, not thepushreturn value. More about storing JSON in local storage here.