Thursday, June 5, 2008

Readonly Textbox Ignores Javascript Input

When using a textbox with a calender extender, you may want to prevent the user from entering any text. Setting the textbox to disabled prevents the browser from processing events on it too.

The other option is to set the ReadOnly property on the textbox. However, when the textbox is clicked and a value is populated using the calendar extender, a postback doesn't process the value of the textbox because for ASP.NET, a readonly textbox is just that - it's readonly and the value does not need to be processed.

Now, for our purposes, having an editable textbox adds to the burden of validation so what we can do is set the textbox to readonly by setting the attribute on the textbox like so:

TextBox1.Attributes.Add("readonly", "readonly");

This approach keeps ASP.NET processing the value of the textbox on postback and keeps the validation to a minimum by preventing the user from entering any 'junk' data.

1 comment: