[javascript] How to disable submit button once it has been clicked?

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='Sending…';
this.form.submit();"

But when it moves to the next page, the parameters did not pass and null values are passed.

This question is related to javascript jquery html jsp form-submit

The answer is


Your question is confusing and you really should post some code, but this should work:

onClick="this.disabled=true; this.value='Sending...'; submitForm(); return false;"

I think that when you use this.form.submit() it's doing what happens naturally when you click the submit button. If you want same-page submit, you should look into using AJAX in the submitForm() method (above).

Also, returning false at the end of the onClick attribute value suppresses the default event from firing (in this case submitting the form).


Using JQuery, you can do this..

$("#submitbutton").click(
   function() {
      alert("Sending...");
      window.location.replace("path to url");
   }
);

I don't think you need this.form.submit(). The disabling code should run, then it will pass on the click which will click the form.


Another solution i´ve used is to move the button instead of disabling it. In that case you don´t have those "disable" problems. Finally what you really want is people not to press twice, if the button is not there they can´t do it.

You may also replace it with another button.


Disabled HTML forms elements aren't sent along with the post/get values when you submit the form. So if you disable your submit button once clicked and that this submit button have the name attribute set, It will not be sent in the post/get values since the element is now disabled. This is normal behavior.

One of the way to overcome this problem is using hidden form elements.


You should first submit your form and then change the value of your submit:

onClick="this.form.submit(); this.disabled=true; this.value='Sending…'; "

You need to disable the button in the onsubmit event of the <form>:

<form action='/' method='POST' onsubmit='disableButton()'>
    <input name='txt' type='text' required />
    <button id='btn' type='submit'>Post</button>
</form>

<script>
    function disableButton() {
        var btn = document.getElementById('btn');
        btn.disabled = true;
        btn.innerText = 'Posting...'
    }
</script>

Note: this way if you have a form element which has the required attribute will work.


I think easy way to disable button is :data => { disable_with: "Saving.." } This will submit a form and then make a button disable, Also it won't disable button if you have any validations like required = 'required'.


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" />

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


In my case this was needed.

Disable submit button on form submit

It works fine in Internet Explorer and Firefox without it, but it did not work in Google Chrome.

The problem is that you are disabling the button before it can actually trigger the submit event.


tested on IE11, FF53, GC58 :

onclick="var e=this;setTimeout(function(){e.disabled=true;},0);return true;"

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);
        }
    });

 
    A better trick, so you don't lose the value of the button is

    function showwait() {
    document.getElementById('WAIT').style['display']='inline';
    document.getElementById('BUTTONS').style['display']='none';
    }
 

wrap code to show in a div

id=WAIT style="display:none"> text to display (end div)

wrap code to hide in a div

id=BUTTONS style="display:inline"> ... buttons or whatever to hide with
onclick="showwait();" (end div)


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?


In this working example, the user confirms in JavaScript that he really wants to abort. If true, the button is disabled to prevent double click and then the code behind which updates the database will run.

<asp:button id="btnAbort" runat="server" OnClick="btnAbort_Click" OnClientClick="if (!abort()) {return false;};" UseSubmitBehavior="false" text="Abort" ></asp:button>

I had issues because .net can change the name of the button

function abort() {
    if (confirm('<asp:Literal runat="server" Text="Do you want to abort?" />')) {
        var btn = document.getElementById('btnAbort');
        btn.disabled = true;
        btn.innerText = 'Aborting...'
        return true;
    }
    else {
        return false;
    }  
}

Because you are overriding the OnClick with OnClientClick, even if your validation method succeeds, the code behind wont work. That's why you set UseSubmitBehavior to false to make it work

PS: You don't need the OnClick if your code is in vb.net!


function xxxx() {
// submit or validate here , disable after that using below
  document.getElementById('buttonId').disabled = 'disabled';
  document.getElementById('buttonId').disabled = '';
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jsp

Difference between request.getSession() and request.getSession(true) A child container failed during start java.util.concurrent.ExecutionException The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path Using if-else in JSP Passing parameters from jsp to Spring Controller method how to fix Cannot call sendRedirect() after the response has been committed? How to include js and CSS in JSP with spring MVC How to create an alert message in jsp page after submit process is complete getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How to pass the values from one jsp page to another jsp without submit button?

Examples related to form-submit

Setting onSubmit in React.js Jquery function BEFORE form submission How to locate and insert a value in a text box (input) using Python Selenium? Submit form without reloading page How to check if text fields are empty on form submit using jQuery? Submitting HTML form using Jquery AJAX Serializing and submitting a form with jQuery and PHP How do I use an image as a submit button? How to pass value from <option><select> to form action validation of input text field in html using javascript