Adam Lee
Adam Lee

Reputation: 586

e.preventDefault() not working on form submission

When my HTML form is submitted, the webpage reloads even though I have the e.preventDefault() command in my submission function.

$("#room-code-form").addEventListener("submit", function(e) {
  e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="room-code-form">
  <input type="text" />
  <input type="submit" />
</form>

Upvotes: 0

Views: 2421

Answers (2)

Avanthika
Avanthika

Reputation: 4182

  1. You have to use on() or bind() with jquery instead of addeventlistener.
  2. Also return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object.

$("#room-code-form").on("submit", function(e) {
  e.preventDefault();
});
<form id="room-code-form">
  <input type="text" />
  <input type="submit" />
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 0

Tushar Gupta
Tushar Gupta

Reputation: 15933

Try using submit function. You need to bind it inside Document Ready function

$(document).ready(function() {
  $("#room-code-form").submit(function(e) {
    e.preventDefault();
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="room-code-form">
  <input type="text" />
  <input type="submit" />
</form>

or

$("#room-code-form").submit(function(e) {
   return false;
});

Upvotes: 1

Related Questions