-1

I'm having a problem with preventDefault() on an event type='submit'.

let submitBookButton = document.querySelector('.submitBook');

submitBookButton.addEventListener('submit', (event) => {
  event.preventDefault();
  let newBook = new Book(titleInput.value, authorInput.value, pagesInput.value, readInput.checked);
  myLibrary.push(newBook);
  console.log(myLibrary);
});

In HTML I also have button type='submit'.

I've tried changing everything I can think of but it still reloads the page on click.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Shulee
  • 3
  • 1

1 Answers1

1

Your trying to attach a submit event to a button, but the submit event should be attached to the form itself.

Here is an example of how you should tackle this:

let bookForm = document.querySelector('.bookForm');

bookForm.addEventListener('submit', (event) => {
  event.preventDefault();
  let titleInput = document.getElementById('titleInput');
  let authorInput = document.getElementById('authorInput');
  let pagesInput = document.getElementById('pagesInput');
  let readInput = document.getElementById('readInput');
  let newBook = new Book(titleInput.value, authorInput.value, pagesInput.value, readInput.checked);
  myLibrary.push(newBook);
  console.log(myLibrary);
});
<form class="bookForm">
  <input type="text" id="titleInput" placeholder="Title">
  <input type="text" id="authorInput" placeholder="Author">
  <input type="text" id="pagesInput" placeholder="Pages">
  <input type="checkbox" id="readInput">
  <button class="submitBook" type="submit">Submit</button>
</form>
jagmitg
  • 4,236
  • 7
  • 25
  • 59