Detect when a form is sent

Posted on

Question :

How can I detect when a form is submitted with pure Javascript?
It would be the equivalent of this in jQuery

  alert('Meu callback');

I was detecting when the user clicked on the submit button, but I recalled that he could also hit enter for example.

Do I have to detect both actions? In this case, when the user clicks submit and when you press the enter key?

Is it possible to achieve the effect just by checking if the form is being sent?


Answer :

$('#form').submit(cb) is a shortcut to $('#form').on("submit", cb) . If you want to avoid jquery you can do this bind of events using onsubmit or addEventListener.

To cancel the submission of the form you can use the preventDefault method or return event handler false:

var meuForm = document.getElementById("meuForm");
meuForm.onsubmit = function(){
        return false;

(Note that the return false might not be reached if the scan logic throws an Exception.) See this question in the English OS

Finally, using the submit event as you are doing covers both the user’s case by clicking on the button and his case by pressing enter.


You can use onsubmit :

<form onsubmit="return minhaFuncao();">

function minhaFuncao()
  alert('Minha funcao');
  // Se retornar true deixa a form ser submetida  
  return false;


Leave a Reply

Your email address will not be published. Required fields are marked *