Monday, June 22, 2009

How to set programmatically a value of a watermarked TextBox via JavaScript

There is an updated version of the article for the latest Ajax Control Toolkit release: http://blog.turlov.com/2010/05/how-to-set-programmatically-value-of.html

If you use ASP.NET AJAX and AJAX Control Toolkit you may find it useful to decorate some of your TextBox controls on a page with a TextBoxWatermark AJAX extender control from the AJAX Control Toolkit. It's fairly easy to use and a nice tool for improving both the page look and user experience.

However if you need to set a value of a TextBox decorated with the TextBoxWatermark extender programmatically via JavaScript on the client-side you may notice that the behavior of the watermarked TextBox is different. If you use the regular way to set a value like this:

$get(textBoxId).value = someText;

then the value displayed in the TextBox on the page will change to the set value but the watermarked look will still be present and other AJAX Control Toolkit TextBox extenders (like a Calendar extender, for instance) will not recognize the new value.

This happens because the TextBoxWatermark extender can not recognize and intercept your JavaScript operation since it's designed to serve user interactions. However there is a correct way of programmatic access to the TextBox's value. We modify the code above like that:

var textBox = $get(textBoxId);
if (textBox.AjaxControlToolkitTextBoxWrapper) {
textBox.AjaxControlToolkitTextBoxWrapper.set_Value(someText);
}
else {
textBox.value = someText;
}

The explanation is that most of the TextBox extenders from the AJAX Control Toolkit including a TextBoxWatermark extender use a special proxy class AjaxControlToolkitTextBoxWrapper to manipulate with the input elements. The proxy adds a special property AjaxControlToolkitTextBoxWrapper to the input element that contains a reference to itself allowing to access the value of the input element correctly. Similarly, if you need to get a value of a watermarked TextBox you do it like this:

var textBox = $get(textBoxId), text;
if (textBox.AjaxControlToolkitTextBoxWrapper) {
text = textBox.AjaxControlToolkitTextBoxWrapper.get_Value();
}
else {
text = textBox.value;
}

2 comments:

  1. This used to work until I upgrade to the latest version of the AjaxToolkit (4.1.40412.0)

    ReplyDelete