0

I want to add books to a library. After entering info to input and submitting the books array stay empty. I'll post pictures so you can understand better. Also sorry for messy code. I'll clean up after getting it to work. console.log after adding a book

const books = [];

const submitBook = () => {
  const bookName = document.querySelector('#title').value;
  const bookAuthor = document.querySelector('#author').value;
  const bookYear = document.querySelector('#year').value;

  // let book = new Book(bookName.value, bookAuthor.value, bookYear.value);

  books.push({
    'name':bookName,
    'author':bookAuthor,
    'year':bookYear
  });

  alert("Book added.");
}
<label for="title">Title:</label><br>
<input type="text" id="title" name="title" required><br>
<label for="author">Author:</label><br>
<input type="text" id="author" name="author" required><br>
<label for="year">Year:</label><br>
<input type="number" id="year" name="year" required><br>
<button onclick="submitBook()">Add book</button>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Henri
  • 15
  • 2
  • 2
    But your code is working! Just try replacing `alert("Book added.")` with `console.log(books)` and you'll see that the array is being added to. – Michael Beeson Dec 13 '20 at 10:25
  • The code in your question does not reproduce the problem you describe. Please change it accordingly. Also, the reason is most likely this: https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron (or your variable is local to the function and you're trying to log it outside) –  Dec 13 '20 at 10:25
  • @MichaelBeeson You're right, there's actually nothing wrong with code. It's just that when I press submit button there's some stuff appearing in console and disappears right away and array stays empty. It's resetting books array every time I submit a book. I have a sample page I'm writing down code from. Our codes are basically identical and other page is working fine, all the info stays in array. That's weird – Henri Dec 13 '20 at 10:48

1 Answers1

0

Your code seems to work. I've taken the liberty to simplify you code somewhat. It is generally not a good idea to use inline event handling (onclick=... within html), so moved the handler to the code section. Also added a button to show added books.

let books = [];
let to = null;
const clearAfter = (delay = 2) => setTimeout(() => console.clear(), delay * 1000);
const format = obj => JSON.stringify(obj).split("},{").join("},\n{");
const submitBook = () => {
  let book = {};
  document.querySelectorAll("input")
    .forEach(inp => book[inp.name] = inp.value);
  books.push(book);
  console.clear();
  // console.log here to see the result immediately,
  // otherwise there may not be any result yet
  console.log(`Added:\n${format(book)}`);
}

document.addEventListener("click", evt => {
  if (evt.target.id === "addbook") {
    submitBook();
  } else if (evt.target.id === "showbooks") {
    console.clear();
    console.log(`${books.length || "No"} added books\n${
      books.length < 1 ? "-" : format(books)}`);
  }
  // remove the log (to make buttons visible again in the SO-run window)
  clearTimeout(to);
  to = clearAfter();
});
<label for="title">Title:</label><br>
<input type="text" id="title" name="title" required><br>
<label for="author">Author:</label><br>
<input type="text" id="author" name="author" required><br>
<label for="year">Year:</label><br>
<input type="number" id="year" name="year" required><br>
<p>
  <button id="addbook">Add book</button>
  <button id="showbooks">Show books added</button>
</p>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Why don’t you just addEventListener to the element with the id of addbook instead of listen to the whole document and then check the if statement every time? Document.getElementById(‘addbook’).addEventListener(‘click’, submitBook) – KienHT Dec 13 '20 at 10:45
  • 1
    It's called [event delegation](https://javascript.info/event-delegation), and it's more versatile in case you need more handlers – KooiInc Dec 13 '20 at 10:48
  • Okay man you rock. Thank you for your effort. Why did you put buttons in

    though? Cheers

    – Henri Dec 13 '20 at 11:07
  • Glad I could help ). `

    ` is for some extra white space (so the buttons are not glued to the last input field).

    – KooiInc Dec 13 '20 at 11:32