Execute javascript code straight before page submit

后端 未结 5 1519
半阙折子戏
半阙折子戏 2020-12-08 19:24

There are a few similar questions to this but none quite the same.

I want to know if there is an event that can be used to execute some JS before a page is submittin

相关标签:
5条回答
  • 2020-12-08 20:07

    Something like this?

    <form onsubmit="do_something()">
    
    function do_something(){
       // Do your stuff here
    }
    

    If you put return like the code below, you can prevent the form submission by returning false from the do_something() function.

    <form onsubmit="return do_something()">
    
    function do_something(){
       // Do your stuff here
       return true; // submit the form
    
       return false; // don't submit the form
    }
    
    0 讨论(0)
  • 2020-12-08 20:10

    You can bind an event handler to the submit event (following code assumes you have an id on your form):

    document.getElementById("someForm").onsubmit = function() {
        //Do stuff
    };
    
    0 讨论(0)
  • 2020-12-08 20:15

    If you are working with the form, you can use onsubmit event.

    Using jQuery you can do that with

    $('#myform').submit(function() {
      // your code here
    });
    
    0 讨论(0)
  • 2020-12-08 20:21

    The following code will abort the submission from the window level, which will not submit the form.

    window.onsubmit = function() { alert('aborting submit'); return false; };
    

    Tested with IE11, so it should work for some legacy applications without jQuery.

    0 讨论(0)
  • 2020-12-08 20:27

    Yes, you can use on the onsubmit event on your form.

    In pure HTML (without jQuery), you can use:

    <form onSubmit="mySubmitFunction()">
       ...
    </form>
    

    More details here: https://www.w3schools.com/jsref/event_onsubmit.asp

    0 讨论(0)
提交回复
热议问题