Tuesday, November 16, 2010

Add JavaScript Dynamically to ASP.NET UpdatePanel

Use the following example:

System.Text.StringBuilder sb = new System.Text.StringBuilder();      
sb.Append(@" var inputs = document.getElementsByTagName('input');                                  for (var i = 0; i < inputs.length; i++) {
         if (inputs[i].type == 'text') {                
            inputs[i].onkeypress = function (event) {
               event = event || window.event;

               return myJavaScriptFunction(event);}
           }}"
       );
ScriptManager.RegisterClientScriptBlock (this, this.GetType(), "ajax", sb.ToString(), true); 

What it does is attaches  a JavaScript function (defined elsewhere) to each input box on the page on the key press event, and then registers it for use with a control that is inside an UpdatePanel.  This could be used for user input validation. The code has been verified in IE and Firefox.

1 comment: