Search code examples
javascriptjqueryjquery-forms-plugin

jQuery Form plugin - how to prevent double submission?


There are several threads on this here at SO but I didn't find one that deals specifically with the awesome jQuery Form plugin which I use extensively in my app.

I want the user to be able to click 'submit' only once -- and disable the 'submit' button until Ajax has returned a JSON string on success.

My trial code goes something like this

$('#submit_button').live('click', function(e) {
e.preventDefault();

var options = {
    type:           'post',
    dataType:       'json',
    beforeSubmit:   function(){
                        $('#loading').show().fadeIn();
                        $('#submit_button').attr('disabled', 'disabled');
                    },
    success:        function(data) {
                            if (data.success === 3) {
                                $('#submit_button').hide();
                                $('#loading').hide();
                                $('#validation_message').html(data.message).fadeIn();
                                $('#submit_button').attr('enabled', 'enabled');
                            }
                    }
            }

$(this).closest('form').ajaxSubmit(options);
});

But this piles up "enabled" and "disabled" attributes in the <button>.

<button class="button" id="submit_button" disabled="disabled" enabled="enabled"> Post </button>

Do you have any suggestions on how to get this to work?


Solution

  • Instead of setting attribute "enabled" to "enabled", you will want to unset the "disabled" attribute: $('#submit_button').attr('disabled', '');

    HTML does not have an "enabled" attribute for buttons, so the browser isn't going to do anything with it - it considers it just a "junk" attribute. Setting and unsetting the "disabled" attribute is what you're after.