Getting the generated name attribute for use in JavaScript

N

Nathan Sokalski

As most of us probably know, ASP.NET controls do not use an exact copy of a
control's ID for the HTML element's name or id attribute. When generating
JavaScript as part of a control or event, we need to have a way to reference
the HTML elements. The only way I have found to reference the HTML elements
in my generated Javascript is the following:

"document.getElementById('" & Me.ctrl.ClientID & "')"

However, this seems like a lot of extra code for each element. Why do the
controls have a ClientID property but not a ClientName property? If there
were a ClientName property, wouldn't it make the code a lot less complicated
and shorten the amount of JavaScript that had to be included with each
control? Or is this just one of those Microsoft things where they are trying
to get people to use the id attribute rather than the name attribute?
 
G

Guest

Why do the
controls have a ClientID property but not a ClientName property? If
there were a ClientName property, wouldn't it make the code a lot less
complicated and shorten the amount of JavaScript that had to be
included with each control? Or is this just one of those Microsoft
things where they are trying to get people to use the id attribute
rather than the name attribute?

You can potentially have two objects using the same ClientName - i.e.:

Form
+MyLabel
+MyUserControl
+MyLabel

Thus the Form can have a MyLabel and a MyUserControl MyLabel... so if you
were to refer to MyLabel, which label is it? :)

But in anycase, you *could* refer to objects by name ... if you know the
exact layout of the page. If you take a close look at the element IDs,
they're generated the same each time (provided the control nesting does not
change).
 
N

Nathan Sokalski

That is irrelevant, and doesn't make sense. First of all, MyLabel is NOT the
same as MyUserControl_MyLabel; if I were to refer to MyLabel only one of
those would match it. Second, using your logic of potentially having two
objects with the same name would apply to the id attribute as well, because
if somebody (for some unknown reason) decided to give a control that was not
runat="server" the same id as the id generated by a runat="server" using

"document.getElementById('" & Me.ctrl.ClientID & "')"

would not know which element to get either, but ASP.NET included a ClientID
property. I see no difference between the potential problems, so why did
they give us ClientID but not ClientName?
 

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

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top