How to prevent default on form submit?

The same way, actually!

// your function
var my_func = function(event) {
    alert("me and all my relatives are owned by China");
    event.preventDefault();
};

// your form
var form = document.getElementById("panda");

// attach event listener
form.addEventListener("submit", my_func, true);
<form id="panda" method="post">
    <input type="submit" value="The Panda says..."/>
</form>

Note: when using .addEventListener you should use submit not onsubmit.

Note 2: Because of the way you’re defining my_func, it’s important that you call addEventListener after you define the function. JavaScript uses hoisting so you need to be careful of order of things when using var to define functions.

Read more about addEventListener and the EventListener interface.

Leave a Comment