How to disable button after clicking submit using jQuery

Last updated on March 10th, 2022 at 07:41 am

Sometimes when user click a submit button multiple times it became an issue at the backend. May be the server side processing the request is not having a logic to track duplicate submission or anything of that sort.

How can we prevent this duplicate submit from happening on the client side ?.

It can be accomplished using jQuery. So instead of writing a complex code in the server side, we can just validate a multiple submission using simple client side validation with the help of jQuery

Let us assume that we have the below HTML form in our code along with the div id links in which the dynamic content will load.

<form id="check"> <input name="username" />
<!-- some more form fields -->
<input id="submit" name="Submit" value="Submit" type="button" />
</form>
<div id="links">
</div>

Now the next step is to add jQuery magic

$(document).ready(function() {
$('#submit').click(function(){
$('#submit').attr('disabled',true);
document.getElementById("links").innerHTML="Loading.."
var refreshId = setInterval( function()
{
$('#links').load("rssreader.php");
clearInterval(refreshId);
}, 6000);
});
});

As you can see above when a user clicks the submit button, it first disables it using

$('#submit').attr('disabled',true);

Then add a innerHTML of “Loading“. After that just for demo I have purposefully simulated form submission with some delay of 6 seconds as shown

var refreshId = setInterval( function()
{
$('#links').load("rssreader.php");
clearInterval(refreshId);
}, 6000);
});

Demo

(NOTE:- Page reviewed Mar 10th 2022, Previous update on 15th Jun 2016. Originally posted on 7th December 2009)

Click to rate this tutorial!
[Total: 5 Average: 4.2]

Leave a Reply

Your email address will not be published. Required fields are marked *