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>
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;
});
on()
or bind()
with jquery instead of addeventlistener. 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.