Friday, July 13, 2007

Dynamically making a field as readOnly using Javascript

I was looking for a sleek solution that would make all the fields of my form read-only dynamically - or atleast make them appear to be readonly.

I decided to use the powerful JQuery library to make this happen. Here is the code that can be put in a JSP/ASP page and included in any page that needs to have all fields as readonly.
$(document).ready(function(){
$(":input,checkbox,radio").addClass("readonlytextbox");
$(":input").focus(function() {this.blur();} );
$("input[@type=checkbox]").click(function()
{alert("Cannot change this field.");
return false;} );
$("input[@type=checkbox]").keydown(function()
{return false;} );
$("input[@type=radio]").click(function()
{return false;} );
$("input[@type=radio]").keydown(function()
{return false;} );
$("select").focus(function()
{alert("Cannot change this field.");
return false;} );
//-- end of code
});