Question : How to register multiple JavaScript functions on a textbox in ASP.Net?

How to register multiple JavaScript functions running on a textbox in ASP.Net?
Bookmark:
Question: Im using a Multiview control having six views. Each of the views has about 10 textboxes and from these 10 checkboxes, there are about 6 textboxes having JavaScript code for events such as onkeypress, onkeyup, onblur, oncopy, onpaste. Right now Im calling all the JavaScript functions from code-behind in Page_OnLoad as:
        Txtbox1.Attributes.Add(onkeypress, javascript: Function1();;
      Txtbox1.Attributes.Add(onkeyup, javascript: Function2();;
      Txtbox1.Attributes.Add(onblur, javascript: Function3();;
       Txtbox1.Attributes.Add(oncopy, return false;);
       Txtbox1.Attributes.Add(onpaste, return false;);

      Txtbox2.Attributes.Add(onkeypress, javascript: Function1();
      Txtbox2.Attributes.Add(onkeyup, javascript: Function2();
      Txtbox2.Attributes.Add(onblur, javascript: Function3();
       Txtbox2.Attributes.Add(oncopy, return false;);
      Txtbox2.Attributes.Add(onpaste, return false;);
'
'
'
'
'
'

      Txtbox6.Attributes.Add(onkeypress, javascript: Function1();
      Txtbox6.Attributes.Add(onkeyup, javascript: Function2();
      Txtbox6.Attributes.Add(onblur, javascript: Function3();
       Txtbox6.Attributes.Add(oncopy, return false;);
       Txtbox6.Attributes.Add(onpaste, return false;);

Although this code works without any errors, the code looks so cluttered. So, Im just wondering if theres any other approach I can use to make my code look a lot cleaner than and not as repetitive as shown above for the 6 textboxes. Please help.

Answer : How to register multiple JavaScript functions on a textbox in ASP.Net?

if all the functions are the same you could create a method to add the javascript to a textbox parameter that is passed in like this:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
private void AddJSToTextBox(TextBox txt)
{
      txt.Attributes.Add("onkeypress", "javascript: Function1();");
      txt.Attributes.Add("onkeyup", "javascript: Function2();");
      txt.Attributes.Add("onblur", "javascript: Function3();");
      txt.Attributes.Add("oncopy" , "return false;");
      txt.Attributes.Add("onpaste", "return false;");
}
 
// then call it like this:
AddJSToTextBox(Txtbox1);
AddJSToTextBox(Txtbox2);
AddJSToTextBox(Txtbox3);
......
AddJSToTextBox(Txtbox6);
Open in New Window Select All
Random Solutions  
 
programming4us programming4us