0

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.

2
  • 1
    The problem is that you're using the return value of push, which is the new length of the array (a number), not the array. If you want to store bookData, use that with JSON.stringify, not the push return value. More about storing JSON in local storage here. Commented Jan 17, 2022 at 11:19
  • Thanks. I will read about it The purpose is I want to store bookName value in local storage but every time a new bookName is entered the previously stored one gets changed. So I am figuring on how to store all the books in the form of an array. Any help would be really appreciated. Commented Jan 17, 2022 at 12:25

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.