jQuery and ASP.NET

June 16, 2009

Prevent User From Editing Text in a TextBox using jQuery




I was recently solving a requirement where a TextBox having text needed to be made read-only, as soon as focus was set on it. This is a typical scenario where a user reloads a form that is to be presented as read-only. This is how I solved the requirement using jQuery:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title></title>

<
script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$("input[type=text]").focus(function() {
if ($(this).val())
$(this).blur().css('background-color', 'gray');
});
});

</script>
</
head>
<
body>
<
form id="form1">
<
div>
<
input id="Text1" type="text" value="Some Text" />
<
input id="Text2" type="text" value="Some Text" />
<
br />
<
input id="Button1" type="button" value="Some Button" />
</
div>
</
form>

</
body>
</
html>

So as soon as you set focus on the textbox, the textbox turns grey indicating that it is read-only and the user is prevented to modify the text.

image



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Prevent User From Editing Text in a TextBox using jQuery"
 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions