Detect when a form is sent



  • 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 reminded him that he can also squeeze enter for example.

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

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


  • QA Engineer

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

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

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

    (It should be noted that the return false may not be achieved if the verification logic releases an exception. See https://stackoverflow.com/questions/3350247/how-to-prevent-form-from-being-submitted

    Finally, using the submit event as you are doing covers both the user's case by clicking the button as the case of it tightening enter.


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2