Detect when a form is sent

Asked

Viewed 148 times

5

How could I detect when a form is sent 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 clicks on the button submit, but I remembered that it can also press enter for example.

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

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

2 answers

5


$('#form').submit(cb) is a shortcut to $('#form').on("submit", cb). If you want to avoid jquery you can make this event bind using onsubmit or addeventlistener.

To unsubscribe from the form you can use the preventDefault or returnar false method from Event Handler:

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

(Note that the Return false may not be reached if the verification logic launches 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 the button and the case of it by pressing enter.

4

You can use the onsubmit:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.