ReadOnly ASP.NET TextBoxes using jQuery

In this post, we will see how to make the ASP.NET TextBox readonly at runtime, using jQuery. This behavior is often seen in applications where a form is opened in Edit mode and some of the textboxes are made readonly, to prevent the user from entering text.

Let’s see how simple it is to use jQuery for this requirement:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Make TextBoxes ReadOnly at RunTime</title>

<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.1.min.js">
</
script>

<
script type="text/javascript">
$(function () {
$('input:text[value!=]').each(function () {
$(this).attr('readonly', true);
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
h2>TextBoxes ReadOnly at RunTime</h2><br />
<
asp:TextBox ID="tbox1" runat="server" Text="SomeText"/><br />
<
asp:TextBox ID="tbox2" runat="server" Text=""/><br />
<
asp:TextBox ID="tbox3" runat="server" Text="SomeText"/><br />
<
br /><br />
Here only those TextBoxes with some value in it,
are made <br /> read-only and cannot be edited
</div>
</
form>
</
body>
</
html>

The code shown above filters those textboxes that have values in it (tbox1 and tbox3) and applies the ‘readonly’ attribute to them. So here you can edit tbox2 but not tbox1 and tbox3

Note: Users can turn off JavaScript so always do server-side validation.

OUTPUT

image

See a Live Demo






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:

Steve Hayter said...

If it's imperative that the information shouldn't be changed, I usually avoid textboxes altogether and just show the values as text.

Or at the very least, ensure you check the values shouldn't be updated server-side. Anyone can go into Firebug (or other dev tools) and just remove the attribute.

Virendra said...

Hi,

There is another way of making the textbox readonly using jQuery. Visit below link.

http://jquerybyexample.blogspot.com/2010/06/make-readonly-textbox-using-jquery.html

Thanks,
Virendra