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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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 Dugar 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