jquery disable submit button on form submission
Asked Answered
S

8

32

For whatever reason, though this code does refresh the page, no fields get posted...

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

Is there a better way of coding this?

Slop answered 26/3, 2011 at 21:26 Comment(6)
Well, after the function performs its action, the form is submitted. Isn't that what you want?Nary
So you are trying to both disable the button (are you trying to use ajax?) and submit the form fields and asking about both? Or just disabling. Disabling isn't going to work if the page is immediately refreshed.Novelty
once they click "submit" the submit button should get disabled, the form should be submitted, and all $_POST variables should be set.Slop
Do all your form fields have the name attibute set?Nary
possible duplicate of Disable submit button on form submitPolynices
Your question is the answer I'm looking for. lol.Businesslike
H
43

Your code is changing the submit action of the form. Instead of submitting, it changes the button attribute.

Try this:

$('input[type=submit]').click(function() {
    $(this).attr('disabled', 'disabled');
    $(this).parents('form').submit();
});
Headland answered 26/3, 2011 at 21:39 Comment(3)
This will not work if the form is submitted through other means (such as pressing enter in a text box).Darbies
that doesn't work either. all i'm trying to do is prevent people from double submitting the form. I.E. once they click "submit" the submit button should get disabled, the form should be submitted, and all $_POST variables should be set.Slop
this breaks HTML5 validation.Billbillabong
I
34

I've seen a few ways to do this:

  • Disable buttons on click
  • Disable buttons on submit
  • Disable form on submit

But none seem to work as expected, so I made my own method.

Add a class to your form called submit-once and use the following jQuery:

$('form.submit-once').submit(function(e){
  if( $(this).hasClass('form-submitted') ){
    e.preventDefault();
    return;
  }
  $(this).addClass('form-submitted');
});

This adds another class to your form: form-submitted. Then, if you try to submit the form again and it has this class, jQuery will prevent the form from submitting and exit the function at return; and thus, nothing gets re-submitted.

I chose to use $('form.submit-once') instead of $('form') because some of my forms use Ajax which should be able to submit multiple times.

You can test it out on this jsFiddle. I added target="_blank" to the form so that you can test submitting the form multiple times.

Side note: you may wish to consider non-JS users by also preventing double submissions server-side. For instance, have a session variable that stores the last submit date/time, and ignore any further submissions within 3 seconds.

Iniquity answered 25/7, 2014 at 13:58 Comment(2)
I like this solution! Disabling the button seemed to cancel out the HTML5 form field validation. But this solution happily lets the browser run the form field validation rules.Greaten
Nice way to control the submissions. No issues found with this approach.Liddle
B
17

I don't know why the code in question does not work. Here's a similar and straightforward code snippet and I advise you to not overcomplicate things.

$("form").submit(function () {
    // prevent duplicate form submissions
    $(this).find(":submit").attr('disabled', 'disabled');
});

Advantages:

  • it works nice with HTML5 Form Validation;
  • it's written in a generic way so it can be re-used "as is";
  • it works if the form is submitted by clicking on submit button as well as if the form is submitted by other means (such as pressing Enter inside a text input).
Billbillabong answered 22/1, 2019 at 1:51 Comment(0)
B
3

What I ended up using, which is working in Chrome 53:

$('input[type=submit]').addClass('submit-once').click(function(e){
    if($(this).hasClass('form-submitted') ){
        e.preventDefault();
        return;
    }
    $(this).addClass('form-submitted');
});
Beethoven answered 20/9, 2016 at 19:3 Comment(0)
D
2

There is no reason your code shouldn't work. When submitting the form, the submit button is disabled. I checked the headers being transmitted to JSFiddle in the demo, and the form field is indeed being sent (tested in IE and Chrome):

POST http://fiddle.jshell.net/josh3736/YnnGj/show/ HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://fiddle.jshell.net/josh3736/YnnGj/show/
Accept-Language: en-US,en;q=0.7,es;q=0.3
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: fiddle.jshell.net
Content-Length: 9
Connection: Keep-Alive
Pragma: no-cache

test=It+works

Your next steps should be:

  • Use something that allows you to inspect the HTTP traffic (my favorite is Fiddler) to see if your form fields are actually being sent to the server. If they are, it's obviously a problem on your server.
  • If the form fields aren't being sent, there's something else going on in your page. Post more of your code so we can see exactly what's happening.
Darbies answered 26/3, 2011 at 22:51 Comment(0)
Y
1

What worked for me....

$('body').bind('pagecreate', function() {
    $("#signin-btn").bind('click', function() {
        $(this).button('disable');
        showProgress(); // The jquery spinny graphic
        $('form').submit();
    });
});
Yellowgreen answered 16/4, 2013 at 22:35 Comment(0)
S
1

Here is a generic solution that works for all inputs, buttons, and links, and displays an image loading icon:

$(function(){
    $(document).on('click', 'input[type=submit], button[type=submit], a.submit, button.submit', function() {

        // Preserves element width
        var w = $(this).outerWidth();
        $(this).css('width', w+'px');

        // Replaces "input" text with "Wait..."
        if ($(this).is('input'))
            $(this).val('Wait...');

        // Replaces "button" and "a" html with a
        // loading image.
        else if ($(this).is('button') || $(this).is('a'))
            $(this).html('<img style="width: 16px; height: 16px;" src="path/to/loading/image.gif"></img>');            

        // Disables the element.
        $(this).attr('disabled', 'disabled');    

        // If the element IS NOT a link, submits the
        // enclosing form.
        if (!$(this).is('a'))    
            if ($(this).parents('form').length)
                $(this).parents('form')[0].submit();

        return true;
    })
});

For links you need to add the class submit.

Solberg answered 11/9, 2015 at 17:42 Comment(0)
V
1

Your code is fine. I ran into this same problem but for me the issue was in the php, not javascript. When you disable the button it is no longer sent with the form and my php was relying on the submit button

if(isset($_POST['submit'])){
   ...
}

So the page refreshes but php doesn't execute. I'm now using a different field which has required attribute.

Vinegar answered 16/11, 2017 at 11:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.