Detect when a form is sent

5

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

$('#form').submit(function(event){
  alert('Meu callback');
  event.preventDefault();
});

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?

    
asked by anonymous 11.08.2014 / 00:24

2 answers

5

$('#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(){
    if(dadosInvalidos()){
        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.

    
11.08.2014 / 01:02
4

You can use onsubmit :

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

function minhaFuncao()
{
  alert('Minha funcao');
  // Se retornar true deixa a form ser submetida  
  return false;
}
    
11.08.2014 / 01:00