[javascript] Disable submit button ONLY after submit

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.

This question is related to javascript jquery button submit

The answer is


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>

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!


Add the disable part in the submit event.

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

$(document).ready(function() {
    $(body).submit(function () {
        var btn = $(this).find("input[type=submit]:focus");
        if($(btn).prop("id") == "YourButtonID")
            $(btn).attr("disabled", "true");
    });
}

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

<form ... onsubmit="myButtonValue.disabled = true; return true;">

  $(function(){

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

thant's it.


Hey this works,

   $(function(){
     $(".submitBtn").click(function () {
       $(".submitBtn").attr("disabled", true);
       $('#yourFormId').submit();
     });
   });

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

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

Test with a setTimeout, that worked for me and I could submit my form, refers to this answer https://stackoverflow.com/a/779785/5510314

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

    function disableButton() {
        $("#btnSubmit").prop('disabled', true);
    }
});

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.


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

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

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 button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to submit

React - clearing an input value after form submit angular2 submit form by pressing enter without submit button spark submit add multiple jars in classpath jQuery's .on() method combined with the submit event Selenium Webdriver submit() vs click() PHP form - on submit stay on same page Disable submit button ONLY after submit HTML - How to do a Confirmation popup to a Submit button and then send the request? HTML form with multiple "actions" Javascript change color of text and background to input value