jquery disable submit button on form submission
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();
});
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.