Monday, May 27, 2013

Disable submit button on form submit

Form submission is one of the most used actions and double form submission is one of most occurred problems in web development. Rather than dealing with this problem server side, eating up your CPU process time, it is much easier and better to deal with this problem client side using JavaScript. When we talk javascript, what it a better way to write it other than using jQuery?!
So this Friday’s quick tip is disabling form submit button on its click or preventing double form submission by disabling submit button.
Consider we have this HTML form in our code:
<form id="myform" action="someUrl.php" method="get">
    <input name="username" />
    <!-- some more form fields -->
    <input id="submit" type="submit" />
</form>
Here is a jQuery code that disables submit button on form submission:
$('#myform').submit(function(){
    $('input[type=submit]', this).attr('disabled', 'disabled');
});
The above jQuery code binds a submit event to our #myform form, then finds its submit button and disables it.

Bonus: disable submit button on form submission for all forms on your page.

// Find ALL <form> tags on your page
$('form').submit(function(){
    // On submit disable its submit button
    $('input[type=submit]', this).attr('disabled', 'disabled');
});

No comments:

Post a Comment