UserControl run Javascript

T

TCORDON

How can I make a UserControl run some javascript when it loads? this is so
the control sets focus to a textbox it contains.

TIA!
 
K

Ken Dopierala Jr.

Hi,

This will do it, just add it to the load event of your User Control:

If (Page.IsClientScriptBlockRegistered("Focus") = False) Then
MyBase.Page.RegisterStartupScript("Focus", "<script
language='javascript'>document.getElementById('" + TextBox1.ClientID +
"').focus();</script>")
End If

Be sure to use control.ClientID and not just hard code the control id
because ASP.Net will change the control id inside a User Control to somthing
like "_ctl0_controlid". Good luck! Ken.
 
T

TCORDON

I added de code you gave me, but I dont know if I am doing something wrong,
the focus is not being set. This is how my conde looks now:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

'Put user code to initialize the page here

If (Page.IsClientScriptBlockRegistered("Focus") = False) Then

MyBase.Page.RegisterStartupScript("Focus",
"<scriptlanguage='javascript'>document.getElementById('" + txtLinea.ClientID
+ "').focus();</script>")

End If

End Sub
 
K

Ken Dopierala Jr.

Hi,

There needs to be a space here between "script" and "language" :
"<scriptlanguage='javascript'>document.getElementById('" +
txtLinea.ClientID

If it still doesn't work then do a view source on your page and post the
outputted HTML. It'll be just above the clsoing </form> tag. Ken.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top