Change Background Color of ASP.NET Button using jQuery

Here’s a simple piece of code that can change the background color of an HTML or ASP.NET Button using jQuery

ASP.NET Button

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Change Background Button Color (from DevCurry.com)</title>
<
style type="text/css">
.bgClr{
background-color:Green;
}
</style>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js">
</
script>
<
script type="text/javascript">
$(function () {
$(".btn").click(function () {
$('.btn').removeClass('bgClr');
$(this).addClass('bgClr');
return false;
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:Button ID="Button1" runat="server" Text="Button One" class="btn" />
<
asp:Button ID="Button2" runat="server" Text="Button Two" class="btn" />
<
asp:Button ID="Button3" runat="server" Text="Button Three" class="btn" />
</
div>
</
form>
</
body>
</
html>

Observe how we have added the class ‘.btn’ to all button elements. On a button click, we first remove the .bgClr class on all buttons and then add the .bgClr class to the button that was clicked. We are using the jQuery addClass and removeClass methods.


HTML Button

The code in the <head> tag remains the same as above. Just use these HTML controls instead of the server controls

<input id="Button1" type="button" value="Button One" class="btn"/>
<
input id="Button2" type="button" value="Button Two" class="btn"/>
<
input id="Button3" type="button" value="Button Three" class="btn"/>

OUTPUT

image

See a Live Demo

If you are using jQuery with ASP.NET Pages, you may find my eBook helpful 51 Recipes with jQuery and ASP.NET Controls






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Anonymous said...

thanks so much for this post. your articles are so easy to follow! I will be looking forward to more tips on asp.net

Anonymous said...

Actually what you are doing is misleading from what you claim to be doing.

You are NOT changing the color of a button, but instead wither applying a background color or leaving it to default.

You can not change a button from red to blue to green for instance.