How to prevent default on form submit?

javascript

Solution

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.

Problem

If I do this I can prevent default on form submit just fine: ``` document.getElementById('my-form').onsubmit(function(e) { e.preventDefault(); // do something }); ``` But since I am organizing my code in a modular way I am handling events like this: ``` document.getElementById('my-form').addEventListener('onsubmit', my_func); var my_func = function() { // HOW DO I PREVENT DEFAULT HERE??? // do something } ``` How can I prevent default now?

Original source

Related problems