0

Is it possible to write a javascript function which can get element by its 'id'

i tried to use this function

function getEleById(ele,IsServerElemt) {
      var elmt ;
      if(IsServerElemt) 
          elmt  = '<%='+ ele + '.ClientID%>' ;
      else 
          elmt = ele;

      return document.getElementById(elmt);
}

Here we have HTML as well as Asp.Net TextBox.

<input type="text" id="txtname" />

<asp:TextBox ID="txtname" runat="server"></asp:TextBox>

and iam trying to call the function as follows

var name = getEleById('txtname',true) ;

here true specifies that txtname is server control

Is it possible to have a generic javascript method for HTML as well Asp.Net controls.

Any help would be appreciated.

Thanks

2
  • 1
    What is ele in this context? Is it a string? A control? You definitely can't mix client side and server side scripting the way you have here. This flat out will not compile properly. Commented Jan 12, 2012 at 18:36
  • ele is a string. var name = getEleById('txtname',true) ; here true specifies that txtname is server control. Commented Jan 12, 2012 at 18:44

3 Answers 3

2

Create your textbox.

<asp:TextBox ID="txtname" runat="server"></asp:TextBox>

You can access it by.

var textbox= $find("<%=txtname.ClientID %>");
Sign up to request clarification or add additional context in comments.

1 Comment

yes i can access the TextBox using $find("<%=txtname.ClientID %>");, but i want to access all the Asp.net controls and HTML control on my page using single javascript function. var txtname = getEleById(txtname ,true); , here true specifies that its an server side control.
1

How about using JQuery's CSS selector?

1) $('.txtName') //JQuery CSS selector

with

<asp:TextBox ID="txtname" class="txtName" runat="server"></asp:TextBox>

You can put all your script in external JS files this way.JQuery CSS Selector

Comments

0

Read through this article. It explains the various ways to generate the element's ID.

What I do is create my textbox like this:

<asp:TextBox ID="txtname" runat="server" ClientIDMode="Static" />

Setting the ClientIDMode to static will set the rendered ID to exactly what you type in the Asp.Net markup. It will render out as something like this:

<input id="txtname" name="?????" />

And then your javascript can be written like this:

function getEleById(elementID) {
    return document.getElementById(elementID);
}

1 Comment

John thanks for the reply ,the ClientIDMode feature is introduced in .net 4.0. iam using .net 3.5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.