96

I wrote this code to disable submit buttons on my website after the click:

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

Unfortunately, it doesn't send the form. How can I fix this?

EDIT I'd like to bind the submit, not the form :)

markzzz
  • 47,390
  • 120
  • 299
  • 507
  • Does this answer your question? [jquery disable submit button on form submission](https://stackoverflow.com/questions/5445431/jquery-disable-submit-button-on-form-submission) – naXa stands with Ukraine Feb 08 '23 at 01:52

15 Answers15

175

Do it onSubmit():

$('form#id').submit(function(){
    $(this).find(':input[type=submit]').prop('disabled', true);
});

What is happening is you're disabling the button altogether before it actually triggers the submit event.

You should probably also think about naming your elements with IDs or CLASSes, so you don't select all inputs of submit type on the page.

Demonstration: http://jsfiddle.net/userdude/2hgnZ/

(Note, I use preventDefault() and return false so the form doesn't actual submit in the example; leave this off in your use.)

Jess
  • 23,901
  • 21
  • 124
  • 145
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
  • Yeah, in fact I really want to bind ALL submit in the page. So I don't mind about ID or CLASS in this way :) Tryed with `$('input[type=submit]').submit(function()` : the form is sent, but the button wont disable anymore... – markzzz Apr 17 '11 at 02:36
  • 5
    You need to put the `submit()` on the form, not the input. See the demo. – Jared Farrish Apr 17 '11 at 02:37
  • Yeah it works! The only problem is that I have a onSubmit function on form, so that's bind by jquery shadow it! I need to implement this on my original function, or change the whole call! Thanks – markzzz Apr 17 '11 at 23:23
  • That's I found strange is that I can't bind a click event on submit, and after another bind on form submit :) – markzzz Apr 17 '11 at 23:24
  • @marzzz - I know, it took me a little while before I understood it too. It has to do with opportunism - you want the Submit event to fire BEFORE your disable submit button happens, so the events on the actual button itself are irrelevant. – Jared Farrish Apr 17 '11 at 23:26
  • Doesnt work for me, although I have [type=image] buttons (and ofc changed the code to that). The form no longer submits when I set them to disabled. I am using Java wicket framework which seem to bomb on IE10 when you click submit buttons quickly after one another. – Johncl Jul 04 '13 at 09:41
  • @Johncl - IE handles `disabled` differently (basically, you can't change it from initial, you have to remove and re-add with the attribute added/removed). I'm not sure, but I also think that `type=image` behave differently as well. – Jared Farrish Jul 04 '13 at 16:41
  • if the above solution doesn't work for you, use find() instead of children(). – rip747 Aug 06 '13 at 21:17
  • 2
    In my case I needed to wrap this in $(document).ready to get it to work. Probably obvious. What wasn't obvious and took a bit of work to figure out is that if the program that is receiving the POST (or GET) is looking for the value of the submit button, if it's disabled then it won't be included in the POST values. At least that's what my testing showed. – Craig Jacobs Jan 13 '14 at 04:17
  • In my case i am getting the desired page in form action with disabled button, but the form action page displayed blank. and stucked there. What to do? – saleem ahmed Jan 13 '16 at 10:15
  • If the page the form is posting back to is returning blank, that sounds like a server-side error. Check your server log (like Apache's) for any errors. – Jared Farrish Jan 14 '16 at 03:27
  • This did not work for me because my submit button is a ` – Jess Dec 14 '16 at 16:12
  • Tested this on a form with JQuery validation that prevents the submit if validation fails, and ended up with the submit button still being disabled by this answer, so just added a check for $(this).valid() before disabling. – Shawn de Wet May 22 '20 at 01:43
  • What is form#id exactly? – A X Dec 23 '20 at 06:43
  • If you want to pass the value of the input button to the $_POST it won't work if the button is disabled – Teo Mihaila Jul 28 '22 at 13:09
41

Specifically if someone is facing problem in Chrome:

What you need to do to fix this is to use the onSubmit tag in the <form> element to set the submit button disabled. This will allow Chrome to disable the button immediately after it is pressed and the form submission will still go ahead...

<form name ="myform" method="POST" action="dosomething.php" onSubmit="document.getElementById('submit').disabled=true;"> 
     <input type="submit" name="submit" value="Submit" id="submit"> 
</form>
Baig
  • 4,737
  • 1
  • 32
  • 47
  • 1
    This is not what the major part of developers want. Javascript stuff _should not_ be inline in the HTML code. Probably using `.on('submit', function() {..})` (or `.submit(function() {..})`) would be better. Even if in this case you could have problems retriggering `.submit()` on the form from inside the callback, falling in an endless loop (at least on a recent version of Opera I'm using, that should use the same engine as Chrome). – Kamafeather Jan 23 '15 at 10:16
  • 14
    This was exactly what I was looking for. A simple inline that doesn't require external libs and doesn't get into way even if JavaScript is disabled. – Seppo Erviälä Oct 15 '15 at 10:15
  • 1
    Tested this on a form with JQuery validation that prevents the submit if validation fails, and ended up with the submit button still being disabled by this answer. – Shawn de Wet May 22 '20 at 01:37
16

Disabled controls do not submit their values which does not help in knowing if the user clicked save or delete.

So I store the button value in a hidden which does get submitted. The name of the hidden is the same as the button name. I call all my buttons by the name of button.

E.g. <button type="submit" name="button" value="save">Save</button>

Based on this I found here. Just store the clicked button in a variable.

$(document).ready(function(){
    var submitButton$;

    $(document).on('click', ":submit", function (e)
    {
        // you may choose to remove disabled from all buttons first here.
        submitButton$ = $(this);
    });

    $(document).on('submit', "form", function(e)
    {
        var form$ = $(this);
        var hiddenButton$ = $('#button', form$);
        if (IsNull(hiddenButton$))
        {
            // add the hidden to the form as needed
            hiddenButton$ = $('<input>')
                .attr({ type: 'hidden', id: 'button', name: 'button' })
                .appendTo(form$);
        }
        hiddenButton$.attr('value', submitButton$.attr('value'));
        submitButton$.attr("disabled", "disabled");
    }
});

Here is my IsNull function. Use or substitue your own version for IsNull or undefined etc.

function IsNull(obj)
{
    var is;
    if (obj instanceof jQuery)
        is = obj.length <= 0;
    else
        is = obj === null || typeof obj === 'undefined' || obj == "";

    return is;
}
Valamas
  • 24,169
  • 25
  • 107
  • 177
7

Simple and effective solution is

<form ... onsubmit="myButton.disabled = true; return true;">
    ...
    <input type="submit" name="myButton" value="Submit">
</form>

Source: here

Zia
  • 641
  • 6
  • 4
5

This should take care of it in your app.

$(":submit").closest("form").submit(function(){
    $(':submit').attr('disabled', 'disabled');
});
3

A more simplier way. I've tried this and it worked fine for me:

$(':input[type=submit]').prop('disabled', true);
Steven
  • 1,996
  • 3
  • 22
  • 33
suresh
  • 73
  • 7
  • 3
    what does this do? how does this help against the described problem above where disabled button will not send the form? – phil294 Aug 16 '19 at 14:26
  • This will prevent the form from being submitted. The asker wanted the form to continue submission even when the button is disabled. – Daniel Wu Nov 02 '20 at 06:19
3

Want to submit value of button as well and prevent double form submit?

If you are using button of type submit and want to submit value of button as well, which will not happen if the button is disabled, you can set a form data attribute and test afterwards.

// Add class disableonsubmit to your form
    $(document).ready(function () {
        $('form.disableonsubmit').submit(function(e) {
            if ($(this).data('submitted') === true) {
                // Form is already submitted
                console.log('Form is already submitted, waiting response.');
                // Stop form from submitting again
                e.preventDefault();
            } else {
                // Set the data-submitted attribute to true for record
                $(this).data('submitted', true);
            }
        });
    });
Community
  • 1
  • 1
Manpreet
  • 2,450
  • 16
  • 21
2

Your code actually works on FF, it doesn't work on Chrome.

This works on FF and Chrome.

$(document).ready(function() {
        // Solution for disabling the submit temporarily for all the submit buttons.
        // Avoids double form submit.
        // Doing it directly on the submit click made the form not to submit in Chrome.
        // This works in FF and Chrome.
        $('form').on('submit', function(e){
          //console.log('submit2', e, $(this).find('[clicked=true]'));
          var submit = $(this).find('[clicked=true]')[0];
          if (!submit.hasAttribute('disabled'))
          {
            submit.setAttribute('disabled', true);
            setTimeout(function(){
              submit.removeAttribute('disabled');
            }, 1000);
          }
          submit.removeAttribute('clicked');
          e.preventDefault();
        });
        $('[type=submit]').on('click touchstart', function(){
          this.setAttribute('clicked', true);
        });
      });
    </script>
Pablo Pazos
  • 3,080
  • 29
  • 42
1

The simplest pure javascript solution is to simply disable the button:

<form id="blah" action="foo.php" method="post" onSubmit="return checkForm();">
  <button id="blahButton">Submit</button>
</form>

document.getElementById('blahButton').disabled = true ;

It works with/without onSubmit. Form stays visible, but nothing can be sumbitted.

rolinger
  • 2,787
  • 1
  • 31
  • 53
1

In my case i had to put a little delay so that form submits correctly and then disable the button

$(document).on('submit','#for',function()
                {
                    var $this = $(this);
                    setTimeout(function (){
                        $this.find(':input[type=submit]').attr('disabled', 'disabled')
                    },1);
                });
h0mayun
  • 3,466
  • 31
  • 40
0

How to disable submit button

just call a function on onclick event and... return true to submit and false to disable submit. OR call a function on window.onload like :

window.onload = init();

and in init() do something like this :

var theForm = document.getElementById(‘theForm’);
theForm.onsubmit =  // what ever you want to do 
Ankit Tyagi
  • 2,381
  • 10
  • 19
0

The following worked for me:

var form_enabled = true;
$().ready(function(){
       // allow the user to submit the form only once each time the page loads
       $('#form_id').on('submit', function(){
               if (form_enabled) {
                       form_enabled = false;
                       return true;
               }

               return false;
        });
});

This cancels the submit event if the user tries to submit the form multiple times (by clicking a submit button, pressing Enter, etc.)

John Langford
  • 1,272
  • 2
  • 12
  • 15
0

I have been using blockUI to avoid browser incompatibilies on disabled or hidden buttons.

http://malsup.com/jquery/block/#element

Then my buttons have a class autobutton:

  $(".autobutton").click(
     function(event) {
        var nv = $(this).html();
        var nv2 = '<span class="fa fa-circle-o-notch fa-spin" aria-hidden="true"></span> ' + nv;
        $(this).html(nv2);
        var form = $(this).parents('form:first');

        $(this).block({ message: null });
        form.submit();                
        });   

Then a form is like that:

<form>
....
<button class="autobutton">Submit</button>   
</form>
Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
0

Button Code

<button id="submit" name="submit" type="submit" value="Submit">Submit</button>

Disable Button

if(When You Disable the button this Case){
 $(':input[type="submit"]').prop('disabled', true); 
}else{
 $(':input[type="submit"]').prop('disabled', false); 
}

Note: You Case may Be Multiple this time more condition may need

0

Easy Method:

Javascript & HTML:

$('form#id').submit(function(e){
    $(this).children('input[type=submit]').attr('disabled', 'disabled');
    // this is just for demonstration
    e.preventDefault(); 
    return false;
});

<!-- begin snippet: js hide: false console: true babel: false -->
<form id="id">
    <input type="submit"/>
</form>

Note: works perfectly on chrome and edge.

Muhammad Ali
  • 956
  • 3
  • 15
  • 20