How to submit form only once after multiple clicking on submit?

后端 未结 9 2149
北荒
北荒 2020-12-13 10:41

I am having problem that when i am trying to submit the form by clicking on the submit button it takes some time to post request during this if i am again click on the Submi

相关标签:
9条回答
  • 2020-12-13 11:22

    One solution is to not use an <input> as the submit button, but instead a <div> (or <span>) styled as a button, having an onclick attribute:

    <form method="post" id="my-form">
      <input type="text" name="input1">
      <input type="text" name="input2">
      <input type="text" name="input3">
    
      ...
    
      <div class="button" id="submit-button" onclick="submitOnce()">
        Submit
      </div>
    </form>
    

    And the submitOnce function would first remove the onclick attribute and then submit the form:

    function submitOnce() {
      document.getElementById('submit-button').removeAttribute('onclick');
      document.getElementById('my-form').submit();
    }
    
    0 讨论(0)
  • 2020-12-13 11:23

    I love the simplicity and directness of Zoidberg's answer.

    But if you want to hook up that handler using code rather than markup (some people prefer to keep markup and code completely separated), here it is using Prototype:

    document.observe('dom:loaded', pageLoad);
    function pageLoad() {
        var btn;
    
        btn = $('idOfButton'); // Or using other ways to get the button reference
        btn.observe('click', disableOnClick);
    }
    function disableOnClick() {
        this.disabled = true;
    }
    

    or you could use anonymous functions (I'm not a fan of them):

    document.observe('dom:loaded', function() {
        var btn;
    
        btn = $('idOfButton'); // Or using other ways to get the button reference
        btn.observe('click', function() {
            this.disabled = true;
        });
    });
    

    Doing it using jQuery will look very similar.

    0 讨论(0)
  • 2020-12-13 11:24

    Disabling the button is one solution, but potentially poses a problem for keyboard users who just hit enter to submit a form. In this scenario, the button won't be disabled. The sure-fire method would be to handle the onsubmit event like so:

    (function () {
        var allowSubmit = true;
        frm.onsubmit = function () {
           if (allowSubmit)
               allowSubmit = false;
           else 
               return false;
        }
    })();
    

    (well, as sure-fire as you can get with JS enabled anyway). You could disabled the button as a visual confirmation to the end user that the form can only be submit once too.

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