[RESOLVED]When using $(this).attr('id'), how can I get the control name without the ct100_MainContent_ prepended to it?

When using $(this).attr(‘id’), how can I get the control name without the ct100_MainContent_ prepended to it? such as when I have div1, I get.

ct100_MainContent_div1 instead of just div1

This is because of how ASP.NET handles determining the ID that is rendered on the client side. ASP.NET uses a system of appending the ID of parent elements (which can be dynamically generated) to give you a unique ID for a particular element (as
ID attributes are required by definition to be unique
).

Assuming that the div1 element in question is a Panel Control, which generates <div> elements, you could try setting the

ClientIDMode property
to "Static" as seen below :

<asp:Panel runat="server" ID="div1" ClientIDMode="Static"></asp:Panel>

which would attempt to render your client-side ID as "div1" to match the ID that you defined in the Panel. Another option might be to simply use a pure HTML div instead (this is more practical if you are not going to be referencing it in your code-behind)
:

<div id="div1"></div>

Finally, if you really needed to just pull the last section of the name using jQuery, you could use a bit of string manipulation from the string.split() function to pull the last value :

<!DOCTYPE html>
<html>
<head>
  <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <script type='text/javascript'>
    $(function(){
      $("div").click(function(){
          // Grab the actual ID (not the ClientID)
          var id = $(this).attr('id').split('_').pop();
          
          // Alert the ID
          alert(id);
      });
    })
  </script>
</head>
<body>
  <div id='ct100_MainContent_div1'>Click Me!</div>
</body>
</html>

You can see an example of this working here.

Leave a Reply