Stop form submit with native javascript

后端 未结 3 674
粉色の甜心
粉色の甜心 2020-12-21 21:25

I need to select a form via native javascript (not jQuery) and prevent the form submission (preventDefault).

The trick is that the form does not have a name or id, a

相关标签:
3条回答
  • 2020-12-21 21:53

    on form submit just return false.

    e.g. <form onsubmit="return false">

    0 讨论(0)
  • 2020-12-21 22:03

    Simple way is use onsubmit event handler

    <script>
    var submitHandler = function() {
      // your code
      return false;
    }
    </script>
    
    <form method="get" onsubmit="return submitHandler()">....</form>
    

    or more easy

    <form onsubmit="return false;">
    
    0 讨论(0)
  • 2020-12-21 22:06

    Using querySelector and an event listener, it's almost like jQuery

    document.querySelector('#search form').addEventListener('submit', function(e) {
        e.preventDefault();
    });
    

    note that the script has to come after the elements, or use a DOM ready handler, so the elements are available.

    FIDDLE

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