IntroductionIn this snippet, I will explain how to disable button after clicked once using JQuery. In the web application we have use the many buttons to do some specific operations.But sometimes users click many times in same button, this is giving unexpected results. So this snippet gives solutions to disable once click button and prevent unexpected result. ImplementationCreate a web application using visual studio and add JQuery Library reference within the page. Html Code <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Disablebuttondemo.aspx.cs"
Inherits="Disablebuttondemo" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to Disable Button after clicked once using JQuery</title>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
</head>
<body>
<form id="form1" runat="server">
<button id="btnsave" class="buttons" value="Save">
Save
</button>
<button id="btnClear" class="buttons" value="Save">
Clear
</button>
</form>
</body>
</html>
Now add two buttons into the page such as Save and Clear it will be like below. <body>
<form id="form1" runat="server">
<div>
<button id="btnsave" class="buttons" value="Save">
Save
</button>
<button id="btnClear" class="buttons" value="Save">
Clear
</button>
</div>
</form>
</body>And then write simple style, to apply for the buttons. CSS <style type="text/css">
.buttons
{
font-size: 12px;
font-weight: bold;
}
</style>And then write javascript to disable button once click with bind and unbind method in jquery. <script language="javascript" type="text/javascript">
$(document).ready(function() {
$('.buttons').bind('click', function() {
alert("You have clicked " + $(this).text() + "Button");
$('.buttons').unbind('click');
});
});
</script>
Now run application and see output as like below, First click the button, the click event will raise, but if you are try to click next time immediately, you not able click. This is help and reduces multiple submission of same values to server mistakes. Live DemoLive demo for disable after clicked once Download Sample Project Download source files -3 kb Hopes help and thank you for reading. |