Connecting JavaScript with a TextBox

Yesterday I was working on a web application where we wanted to have a JavaScript function run when the user changes a TextBox. It was a simple function, which took three input values and performs calculations to generate two additional values. I soon discovered two issues when working with JavaScript in ASP.NET. The first is that the TextBox control is server-side, so it doesn’t include the client-side “onclick” attribute. Second, is that when .NET generates the input box, it adds the ID of the parent container to the ID of the TextBox, for example ID=”TextBox1″ may become ID=”ctl00_ContentPlaceHolder1_TextBox1″.

Doing an Internet search, I found two solutions to the first issue. One option is to include the attribute onchange=”myJavaScriptFunction()” in the TextBox control. Visual Studio will give you a warning, but it does work. The second option is to include the following line of code in the Page_ Load function:

TextBox1.Attributes.Add("onchange", "myJavaScriptFunction()");

I prefer this method because Visual Studio doesn’t flag it.

To solve the second issue, I found an example where they used the ClientID attribute of the TextBox Control to find the element in JavaScript. Here is a sample JavaScript Function that does a popup alert, giving the value that was entered in TextBox1:

function myJavaScriptFunction()
{
  var myField = document.getElementById("<%= TextBox1.ClientID %>");

  alert(myField.value);
}

This is a kind of ugly, but it works. You can create as many variables as you need to point to your .NET controls. The function I wrote yesterday had 5 of these temporary variables. Seems like a lot of work to assign values to a couple readonly fields in the form.

Advertisements
%d bloggers like this: