Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

preventDefault() not stopping page reload

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading