How can I listen to the form submit event in javascript? How can I listen to the form submit event in javascript? javascript javascript

How can I listen to the form submit event in javascript?


Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?

var ele = /*Your Form Element*/;if(ele.addEventListener){    ele.addEventListener("submit", callback, false);  //Modern browsers}else if(ele.attachEvent){    ele.attachEvent('onsubmit', callback);            //Old IE}

callback is a function that you want to call when the form is being submitted.

About EventTarget.addEventListener, check out this documentation on MDN.

To cancel the native submit event (prevent the form from being submitted), use .preventDefault() in your callback function,

document.querySelector("#myForm").addEventListener("submit", function(e){    if(!isValid){        e.preventDefault();    //stop form from submitting    }});

Listening to the submit event with libraries

If for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:

  1. jQuery

    $(ele).submit(callback);

    Where ele is the form element reference, and callback being the callback function reference. Reference