Disable submit button ONLY after submit
Asked Answered
S

13

48

I have the following HTML and jquery:

<html dir="ltr" lang="en">
<head>
</head>
<body>

<h2>Test disabling submit button for 1 minute...</h2>

<br/>

<p style="text-align:center"> 
<form id="yourFormId" name="yourFormId" method="post" action="#">
 <input type="submit" class="submitBtn" value="I Accept"/>
</form>
</p>




<!--script to disable the submit button -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">  
</script>
<script type="text/javascript">

$(document).ready(function () {
    $(".submitBtn").click(function () {
        $(".submitBtn").attr("disabled", true);
        return true;
    });
});

</script>
<!--script ends here-->

</body>
</html>

As its stands the submit button gets disabled when pressed. However once pressed it does not seem perform the submit. If I removed the jquery to disable the button, the button then performs the submit normally.

How can I disable the button only after it has performed the submit? the current jquery above seems to conflict with the submit operation.

Any suggestions to resolve this issue would be extremely helpful.

Spense answered 14/6, 2013 at 10:55 Comment(1)
Can you not simply use the onMouseUp even in JS to dissable the button.Erminna
M
51

Add the disable part in the submit event.

$(document).ready(function () {
    $("#yourFormId").submit(function () {
        $(".submitBtn").attr("disabled", true);
        return true;
    });
});
Marius answered 14/6, 2013 at 10:56 Comment(5)
@GeoffreyFernandez it definitely works. You must be doing something incorrectly.Papert
It works perfectly, @GeoffreyFernandez check your form and btn id'sGonzalez
For me this is disabling the submit button completely so even the first click doesn't get through.Goodden
This doesn't work if the <button> has a value="" attribute - browsers don't submit disabled controls (input, button, select, textarea) if they're disabled, and that happens right after the onsubmit event, not before it.Sonnie
If anyone was wondering submitBtn is the class of the submit button (in my case class="btn", so I used $(".btn").attr... etcHydrolyse
F
26

I faced the same problem. Customers could submit a form and then multiple e-mail addresses will receive a mail message. If the response of the page takes too long, sometimes the button was pushed twice or even more times..

I tried disable the button in the onsubmit handler, but the form wasn't submitted at all. Above solutions work probably fine, but for me it was a little bit too tricky, so I decided to try something else.

To the left side of the submit button, I placed a second button, which is not displayed and is disabled at start up:

<button disabled class="btn btn-primary" type=button id="btnverzenden2" style="display: none"><span class="glyphicon glyphicon-refresh"></span> Sending mail</button>   
<button class="btn btn-primary" type=submit name=verzenden id="btnverzenden">Send</button>

In the onsubmit handler attached to the form, the 'real' submit is hidden and the 'fake' submit is shown with a message that the messages are being sent.

function checkinput // submit handler
{
    ..
    ...
    $("#btnverzenden").hide(); <= real submit button will be hidden
    $("#btnverzenden2").show(); <= fake submit button gets visible
    ...
    ..
}

This worked for us. I hope it will help you.

Fredella answered 19/3, 2015 at 13:39 Comment(2)
this is the most amazing solution i have found - my jQ validation script fails to work with .attr("disabled", "true"); ... form just doesn't send, while submit button gets disabled ... your answer is gold! ... but yea it a hack :)) thank you!!!Disloyal
Thanks for this. Pretty straight forward.Robby
G
17

This solution has the advantages of working on mobile and being quite simple:

<form ... onsubmit="myButtonValue.disabled = true; return true;">
Grussing answered 26/6, 2015 at 14:27 Comment(4)
In Chrome, this appears to prevent the name/value of the button pressed from being submitted to the server. Important if you have a button with name="save" and a button with name="cancel" and you needed to know which one the user pressed.Hives
by far the best, shortest solution...and the only one that worked for meCheka
worked beautifully for meCartomancy
see also https://mcmap.net/q/130778/-disable-submit-button-on-form-submit - a clearer answer imho - i dont understand what to replace myButtonValue withInnkeeper
H
15

Hey this works,

   $(function(){
     $(".submitBtn").click(function () {
       $(".submitBtn").attr("disabled", true);
       $('#yourFormId').submit();
     });
   });
Hedjaz answered 14/6, 2013 at 11:23 Comment(5)
I found a bug where it submits the form twice in IE 11. Please be mindful with this implementation.Stylet
Unfortunately I confirm what Dot Batch said, moreover the same behavior could happen in IE10....Kevin
it is a bug in the code - you should declare parameter "e" to the click handler and call e.preventDefault(); on it.Malleable
There is a separate issue here in that if the button is disabled when the form is submitted, then the value of the button pushed is not submitted with the form. So if you have a form with <input type="submit" name="save" value="Save"> you will not receive save=Save in the form data when it is pushed.Hives
this implementation blocks the submission completely for me in chrome.Kyles
B
11

As a number of people have pointed out, disabling the submit button has some negative side effects (at least in Chrome it prevents the name/value of the button pressed from being submitted). My solution was to simply add an attribute to indicate that submit has been requested, and then check for the presence of this attribute on every submit. Because I'm using the submit function, this is only called after all HTML 5 validation is successful. Here is my code:

  $("form.myform").submit(function (e) {
    // Check if we have submitted before
    if ( $("#submit-btn").attr('attempted') == 'true' ) {
      //stop submitting the form because we have already clicked submit.
      e.preventDefault();
    }
    else {
      $("#submit-btn").attr("attempted", 'true');
    }
  });
Buttonball answered 11/12, 2017 at 23:36 Comment(1)
+1 Setting the 'disabled' attribute on the submit button makes the form submission not include the button name/value so if your server-side code is expecting to find that parameter, it will be missing. this suggestion actually worked because it actually prevents the default behavior (form submit) on a duplicate submissionJolandajolanta
U
7

Test with a setTimeout, that worked for me and I could submit my form, refers to this answer https://mcmap.net/q/53040/-why-is-settimeout-fn-0-sometimes-useful

$(document).ready(function () {
    $("#btnSubmit").click(function () {
        setTimeout(function () { disableButton(); }, 0);
    });

    function disableButton() {
        $("#btnSubmit").prop('disabled', true);
    }
});
Unquote answered 22/4, 2016 at 19:39 Comment(3)
Tried this as it looks like an elegant solution, and although it disables the button it did not stop me from double-clicking the button (if clicked fast enough).Imposing
Try to call Jquery function .off() after the click event and before your actions and the setTimeout like $(this).off("click");. Then when needed rebind the button to click eventUnquote
This was definitely the simplest solution for me. I'm working in ASP.NET web forms which adds its own click and submit handlers, and this works without having to interfere with any of that.Misestimate
O
5

Reading the comments, it seems that these solutions are not consistent across browsers. Decided then to think how I would have done this 10 years ago before the advent of jQuery and event function binding.

So here is my retro hipster solution:

<script type="text/javascript">
var _formConfirm_submitted = false;
</script>
<form name="frmConfirm" onsubmit="if( _formConfirm_submitted == false ){ _formConfirm_submitted = true;return true }else{ alert('your request is being processed!'); return false;  }" action="" method="GET">

<input type="submit" value="submit - but only once!"/>
</form>

The main point of difference is that I am relying on the ability to stop a form submitting through returning false on the submit handler, and I am using a global flag variable - which will make me go straight to hell!

But on the plus side, I cannot imagine any browser compatibility issues - hey, it would probably even work in Netscape!

Offering answered 25/2, 2016 at 10:55 Comment(1)
Oh the good old root days of www, without fancy bulk libraries to distract the wannabes.Aloysius
C
4

This is the edited script, hope it helps,

   <script type="text/javascript">
        $(function(){
            $("#yourFormId").on('submit', function(){
                return false;
                $(".submitBtn").attr("disabled",true); //disable the submit here
                //send the form data via ajax which will not relaod the page and disable the submit button
                $.ajax({
                   url      : //your url to submit the form,
                   data     : { $("#yourFormId").serializeArray() }, //your data to send here 
                   type     : 'POST',
                   success  : function(resp){
                        alert(resp);    //or whatever 
                   },
                   error    : function(resp){

                   }
                });
            })
        });
    </script>
Comatose answered 14/6, 2013 at 11:12 Comment(3)
I want to disable the button after it has submitted... so that no more submits can be doneSpense
are you posting your form via ajax? otherwise the page will automatically reload and there is no need for disabling the button.Faubert
Nothing is executed after a returnAdjudge
S
4

I put this in my global code to work on all submit buttons:

$("input[type='submit']").on("click", function (e) {
    $(this).attr("disabled", true);
    $(this).closest("form").submit()
});
Syncarpous answered 4/1, 2016 at 5:5 Comment(0)
F
4

My problem was solved when i add bind section to my script file.

Totally i did this 2 steps :

1 - Disable button and prevent double submitting :

$('form').submit(function () {
    $(this).find(':submit').attr('disabled', 'disabled');
});

2 - Enable submit button if validation error occurred :

$("form").bind("invalid-form.validate", function () {
    $(this).find(':submit').prop('disabled', false);
});
Fad answered 24/12, 2016 at 5:30 Comment(0)
U
3

Not that I recommend placing JavaScript directly into HTML, but this works in modern browsers (not IE11) to disable all submit buttons after a form submits:

<form onsubmit="this.querySelectorAll('[type=submit]').forEach(b => b.disabled = true)">
Utoaztecan answered 25/11, 2020 at 9:38 Comment(0)
O
2

I went through a lot of solutions for my problem statement and I think most of the people here are also answering the same.

Generally, when you do a server side form submit, there is a chance of user clicking the button multiple times which leads to multiple submissions. So, to prevent that, the button should be disabled after the first submit. This is what worked for me in the most elegant way.

  1. We have a form submit event <form onsubmit="onFormSubmitted()"></form>.
  2. In onFormSubmitted() disable your submit button or do any operations required.
  3. Handing this way retains your html validations as well as it disables the button once the form submit is triggered when first click of button takes place.

function onSubmit() {
  $('.btn_submit').attr('disabled', true);
}
<form class="contact_form" method="POST" autocomplete="off" onsubmit="onSubmit()">

  <input name="email" id="email">
  <button class="btn_submit" type="submit">Submit</button>

</form>

Alternatively, you can also make global form submit handler for forms throughout the project.

$('form').on('submit', function() {
   $(this).find(":submit").prop('disabled', true);

 });
Optimism answered 27/10, 2021 at 5:11 Comment(0)
D
-4
  $(function(){

    $("input[type='submit']").click(function () {
        $(this).attr("disabled", true);   
     });
  });

thant's it.

Deplorable answered 25/2, 2016 at 11:3 Comment(2)
Please, add some explanation. :)Transeunt
-1. This code does the same job as OP's code. Secondly, it prevents the form from submitting (this is what OP had issue with in the first place).Artimas

© 2022 - 2024 — McMap. All rights reserved.