Java script using in User Control

by Syed Aziz ur Rahman 14. July 2004 03:59

Dear All,
Let me give you an example to explain the usage of javascript in user controls. Let us suppose that u have a usercontrol in which there are 2 textboxes named txt1 and txt2 and a button called btn1 and u want to add some custom checking when the button is clicked.

Make the usercontrol. Put it in a page and see the page in IE. View the source and check the ids of the textboxes and button. You will notice that the ids are "prefixed" by some "ambigous" letters like ctl0:, ctl1 etc.

Asp.net do this prefixing in order to maintain the unique ids of the server controls. Can u think what will happen if there are 2 instance of same user control on a single page? The ids will be like clt0:txt1 and clt1:txt1 for the textbox we named txt1. This is the scenario

So the catch is when u want to use your own javascript, pass the "ClientID" attribute of the textbox to the function. For example the javascript funtion should be like

function ValidateTextBoxes(txt1, txt2)
//do the magic validation

In your code behind u will do like this
btn1.attribute.add("onclik" ."ValidateTextBoxes('" & txt1.ClientID & "'," & txt2.ClientID & "')"). Now u can easily use functions like getElementbyID and dont forget to use the parameters passed in the function.

I know that my writing capabilites is not so good. But i have tried to explain it as good as i can in this short time.

If any problems. email me and i will send you some working sample

Allah Hafiz




Powered by BlogEngine.NET
Original Design by Laptop Geek, Adapted by onesoft