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

event.preventDefault() doesn't work on form submission

This sounds like the stupidest problem I’ve ever encountered, but this simple thing doesn’t work. The page refreshes every time I press ‘Submit’ button. Any ideas why?

Here is my code:

const submitBtn = document.querySelector('.submit-btn');

const submitForm = function (event) {
  event.preventDefault();
  console.log('Hi');
};

submitBtn.addEventListener('submit', submitForm);
<form>
    <label>Input your facebook profile URL</label>
    <input type="text" />
    <button class="submit-btn">Submit</button>
</form>

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 :

As others point out, the submit event is on the form, not the button. You can use the form property of the button:

submitBtn.form.addEventListener('submit', submitForm);
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