How to prevent default on form submit?

后端 未结 2 1248
别那么骄傲
别那么骄傲 2020-12-17 01:30

If I do this I can prevent default on form submit just fine:

document.getElementById(\'my-form\').onsubmit(function(e) {
   e.preventDefault();
   // do some         


        
相关标签:
2条回答
  • 2020-12-17 02:11

    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
    }
    
    0 讨论(0)
  • 2020-12-17 02:13

    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.

    0 讨论(0)
提交回复
热议问题