JavaScript Referencing Server Controls (such as <asp:TextBox...)

  • Thread starter Thread starter Alex Maghen
  • Start date Start date
A

Alex Maghen

In ASP.NET 3.5, I want to understand the most elegant and recommended method
for writing JavaScript into a page generated from an .ASPX.

What I mean is, for example, the IDs of various page controls get completely
changed when the Control is a runat="server". So, for example, if I have a
control <asp:TextBox id="MyTB" runat="server"..., when I go to reference it
from JavaScrip on the client side, their's a good chance that the ACTUAL ID
of the text box will no longer be "MyTB" because of things like MasterPages,
etc.

Is there some kind of ServerControl in ASP.NET 3.5 that allows me to write
clean, elegant JavaScript on the server side that somehow gets properly
translated to handle these (and other) changes that ASP.NET makes to the page
controls?

Alex
 
Just would like to add that I usually have a helper function in my main js
file
function $$(elementId)
{
return document.getElementById(elementId);
}

So document.getElementById('<%=MyTB.ClientID%>');
becomes $$('<%=MyTB.ClientID%>');


George.
 
I do not care much about streaming less characters to the browser (As long
as it's reasonable).
I usually care about how much I am typing plus avoiding misspells in
getElementById.
For me it's hard to type Id (see getElementById) and ID (see ClientID) in
one sentence without mistake :)

Plus lately I am using extensively JQuery and like the $('#myid') way to
reference JQuery wrappers. Hence I have $$('myid') when I do not need JQuery
wrapper.

George.
 
Hi Alex,

The answer provided by Mark and George are all reasonable. If you still
cannot get it work or have further questions please feel free to ask. I'll
try my best to follow up.

Regards,
Allen Chen
Microsoft Online Community Support
 
Back
Top