If I do this I can prevent default on form submit just fine:
document.getElementById(\'my-form\').onsubmit(function(e) {
e.preventDefault();
// do some
i known this is old, but just for the sake of it. try
document.getElementById('my-form').addEventListener('onsubmit',
function(event){event.preventDefault();my_func();});
var my_func = function() {
// HOW DO I PREVENT DEFAULT HERE???
// do something
}
The same way, actually! demo
Some HTML
<form id="panda" method="post">
<input type="submit" value="The Panda says..."/>
</form>
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.