Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery disable submit button on form submission

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?

like image 928
scarhand Avatar asked Mar 26 '11 21:03

scarhand


People also ask

How do you disable submit button on form submit?

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.

How disable submit button until form is filled jQuery?

click(function () { if ($('#submit-button').is(':disabled')) { $('#submit-button'). removeAttr('disabled'); } else { $('#submit-button'). attr('disabled', 'disabled'); } });

How do I stop a form from submitting in jQuery?

We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.


2 Answers

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(); }); 
like image 172
Diodeus - James MacFarlane Avatar answered Sep 17 '22 18:09

Diodeus - James MacFarlane


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.

like image 34
rybo111 Avatar answered Sep 17 '22 18:09

rybo111