If I do this I can prevent default on form submit just fine:
document.getElementById(\'my-form\').onsubmit(function(e) {
e.preventDefault();
// do some
The same way, actually! demo
Some HTML
Your JavaScript
// 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);
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.