How to disable submit button once it has been clicked?

后端 未结 18 1359
轻奢々
轻奢々 2020-12-01 05:06

I have a submit button at the end of the form.

I have added the following condition to the submit button:

onClick=\"this.disabled=true;
this.value=\'         


        
相关标签:
18条回答
  • 2020-12-01 05:28

    If you disable the button, then its name=value pair will indeed not be sent as parameter. But the remnant of the parameters should be sent (as long as their respective input elements and the parent form are not disabled). Likely you're testing the button only or the other input fields or even the form are disabled?

    0 讨论(0)
  • 2020-12-01 05:28

    Here's a drop-in example that expands on Andreas Köberle's solution. It uses jQuery for the event handler and the document ready event, but those could be switched to plain JS:

    (function(document, $) {
    
      $(function() {
        $(document).on('click', '[disable-on-click], .disable-on-click', function() {
          var disableText = this.getAttribute("data-disable-text") || 'Processing...';
    
          if(this.form) {
            this.form.submit();
          }
    
          this.disabled = true;
    
          if(this.tagName === 'BUTTON') {
            this.innerHTML = disableText;
          } else if(this.tagName === 'INPUT') {
            this.value = disableText;
          }
        });
      });
    
    })(document, jQuery);
    

    It can then be used in HTML like this:

    <button disable-on-click data-disable-text="Saving...">Click Me</button>
    <button class="disable-on-click">Click Me</button>
    <input type="submit" disable-on-click value="Click Me" />
    
    0 讨论(0)
  • 2020-12-01 05:29

    Probably you're submitting the form twice. Remove the this.form.submit() or add return false at the end.

    you should end up with onClick="this.disabled=true; this.value='Sending…';"

    0 讨论(0)
  • 2020-12-01 05:29

    I did the trick. When set timeout, it works perfectly and sending all values.

        $(document).ready(function () {
            document.getElementById('btnSendMail').onclick = function () {
                setTimeout(function () {
                    document.getElementById('btnSendMail').value = 'Sending…';
                    document.getElementById('btnSendMail').disabled = true;
                }, 850);
            }
        });
    
    0 讨论(0)
  • 2020-12-01 05:30

    tested on IE11, FF53, GC58 :

    onclick="var e=this;setTimeout(function(){e.disabled=true;},0);return true;"
    
    0 讨论(0)
  • 2020-12-01 05:30

    the trick is to delayed the button to be disabled, and submit the form you can use window.setTimeout('this.disabled=true',0); yes even with 0 MS is working

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