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?
Enable / Disable submit button 1.1 To disable a submit button, you just need to add a disabled attribute to the submit button. $("#btnSubmit"). attr("disabled", true); 1.2 To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.
click(function () { if ($('#submit-button').is(':disabled')) { $('#submit-button'). removeAttr('disabled'); } else { $('#submit-button'). attr('disabled', 'disabled'); } });
We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With