Search code examples
javascriptpure-js

Pure JS. How to add event listener for submit any form


i tried to addEventListener once for all forms on page to serialize and check them before ajax sending. If you have an pill for my broken head, share it pls

window.addEventListener('submit', function(e){

        //Serialize Form
        //Ajax send

    }, false);

thx much


Solution

  • You can query all forms and add event listener to each item:

    document.querySelectorAll('form').forEach(form => form.addEventListener('submit', function(e){
      e.preventDefault();
      console.log('test');
    }, false));
    <form>
      <button>submit</button>
    </form>