How to disable submit button once it has been clicked?
Asked Answered
R

19

100

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.

Rajasthan answered 29/7, 2010 at 20:50 Comment(2)
This is probably not the fault of the calls you show. Please show the full HTML of the form.Deicer
Don't use the onclick event of the submit button - use the onsubmit event of the form. Otherwise you won't catch a submission from the keyboard.Partly
S
73

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…';"

Stereoisomerism answered 29/7, 2010 at 20:53 Comment(5)
Careful though as this does not work in IE8 and Chrome...well it works in that it does what the script says to do, but a consequence is that it also disables the submitting of the form.Irresolution
See @andreaskoberle's answerIrresolution
for button type=submit tags replace this.value with this.innerTextIncidental
@Andreas Köberle answer below is better, especially if using any of the ASP.NET frameworks.Triphammer
its 2022, and this solution works perfectly on Chrome 102.0.5005.115Hereditament
P
145

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

onClick="this.form.submit(); this.disabled=true; this.value='Sending…'; "
Plasm answered 29/7, 2010 at 20:59 Comment(9)
This is the best answer. Some browsers don't know to submit the form beforehand, and this solution works around that.Lilytrotter
onclick should be lowercaseClaudetta
Won't work as expected if HTML5 validation is triggered first.Passenger
For me, 'this.disabled=true' prevents back end function from firing, even though it appears after the submit! To get around this I implemented a bool value and if statement to check first or subsequent clicks, and returned false for subsequent.Nerta
Working with ASP.NET Update Panel I disabled the Submit behavior. 'OnClick="btnSave_Click" OnClientClick="this.disabled=true; this.value='Saving ... Please Wait.';" UseSubmitBehavior="false"'Ligurian
doesn't respect formaction attributeCown
in a javascript handler, this would instead be event.currentTarget.Cavell
This doesn't work for me. The values of the form do not submit.Flute
Note, if you're trying to submit an AJAX / remote form, use this.form.requestSubmit() instead. Works a treat!Heimer
S
73

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…';"

Stereoisomerism answered 29/7, 2010 at 20:53 Comment(5)
Careful though as this does not work in IE8 and Chrome...well it works in that it does what the script says to do, but a consequence is that it also disables the submitting of the form.Irresolution
See @andreaskoberle's answerIrresolution
for button type=submit tags replace this.value with this.innerTextIncidental
@Andreas Köberle answer below is better, especially if using any of the ASP.NET frameworks.Triphammer
its 2022, and this solution works perfectly on Chrome 102.0.5005.115Hereditament
C
38

tested on IE11, FF53, GC58 :

onclick="var e=this;setTimeout(function(){e.disabled=true;},0);return true;"
Charlesettacharleston answered 14/6, 2017 at 15:19 Comment(2)
This should be accepted ; others doesn't send the formBleary
This works great, but how do I change the "value" when clicked?Phobe
C
27

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.

Crump answered 7/11, 2018 at 6:4 Comment(0)
C
10

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.

Centreboard answered 29/7, 2010 at 20:58 Comment(0)
S
7

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

Shuddering answered 29/7, 2010 at 22:22 Comment(1)
but what if the user presses the button in that fraction of time ?Adaptation
S
4

Using JQuery, you can do this..

$("#submitbutton").click(
   function() {
      alert("Sending...");
      window.location.replace("path to url");
   }
);
Sammiesammons answered 30/7, 2010 at 5:18 Comment(1)
Please don't use alerts for that, they block the page until clickedIncidental
C
2

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?

Colbycolbye answered 29/7, 2010 at 20:58 Comment(0)
O
2
function xxxx() {
// submit or validate here , disable after that using below
  document.getElementById('buttonId').disabled = 'disabled';
  document.getElementById('buttonId').disabled = '';
}
Olmos answered 3/12, 2013 at 8:16 Comment(0)
C
2

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" />
Chic answered 8/9, 2016 at 14:29 Comment(1)
I like this solution because it follows the 'Don't Repeat Yourself' (DRY) principle. Once the first chunk is added you can re-use it simply by using a class.Homogeny
L
1

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.

Logging answered 29/7, 2010 at 20:52 Comment(2)
If you don't put "this.form.submit()" then form will not submit in this case.Gabbey
i am using <button type="button" class="addb btn btn-primary rounded-pill py-2 btn-block" type="submit" data-voice_sku="'.$row["voice_sku"].'" data-voice_name="'.$row["voice_name"].'" onclick="this.disabled=true">Add to Playlist</button> if i refresh the page disable gone, how to solve this?Millican
A
1

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.

Aguayo answered 24/7, 2013 at 13:53 Comment(0)
A
0

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).

Apophyge answered 29/7, 2010 at 20:56 Comment(0)
G
0
 
    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)

Grippe answered 19/10, 2013 at 16:51 Comment(0)
B
0

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.

Bisutun answered 23/7, 2015 at 16:57 Comment(1)
It's generally good practice to show the appropriate code in your answer, instead of just a link.Maurizia
G
0

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'.

Grindle answered 8/8, 2017 at 9:9 Comment(1)
This behavior seems to be Ruby on Rails specific.Incidental
D
0

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!

Dakota answered 6/5, 2019 at 20:21 Comment(0)
H
0

Okay, I did a lot of research on how to make this work perfectly. So the best option is to create a set timeout for disabling a button onclick.

Now, the problem arise when there is a submit function running on the backend. Then the events become stacked in a queue and whenever the javascript "button.disabled == true"is added to the onclick event, only the first action(i.e. disabling the button) gets triggered and not the submit action which is running in the backend (this backend submit function can comprise of anything such as $.ajax).

For disabling Single button on click :

function() {  // I always create anonymous function to avoid polluting global space
    var btn = document.getElementsByClassName("btn");
    btn.onclick = function() {
        setTimeout(function() {
            backButton.disabled = true;
        }, 0);
    };
}
}();

This code will disable your button and also would run the function on the queue. timeout = 0 actually is used for firing subsequent backend tasks.

For disabling all btns in the screen :

(function() {
    let i, element, list, o;
    element = document.getElementsByClassName("classx");
    if (element) {
        element = element[0];
        list = element.getElementsByTagName("button");
        for (i = 0; i < list.length; i++) {
            o = list[i];
            o.onclick = function() {
                setTimeout(function() {
                    let i;
                    for (i = 0; i < list.length; i++) {
                        list[i].disabled = true;
                    }
                }, 0);
                return true;
            }
        }
    }
})();

This would help you disable all of the buttons present in the page (just use it according to your usecase).

Also, this (disabled button) is a good use case for settimeout=0, functionality description as it will "defer" the call until the currently "stacked javascript events" are finished.

Thank you and hope this helps someone's in the future.

Hospitality answered 1/12, 2022 at 2:22 Comment(0)
C
-1

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);
        }
    });
Cartelize answered 9/3, 2018 at 1:27 Comment(1)
people will click several times in 850msMorrell

© 2022 - 2024 — McMap. All rights reserved.