0

In my project am create dynamic controls when page load based on database values. now i need to add click event for asp:label in jquery so i tried like this.

ASP.NET

        xShowVersion.Style(HtmlTextWriterStyle.Top) = xTop & "px"
        xShowVersion.Style.Add(HtmlTextWriterStyle.Height, "40px")
        xShowVersion.Style.Add(HtmlTextWriterStyle.Width, "480px")
        xShowVersion.Style.Add(HtmlTextWriterStyle.Position, "absolute")
        xShowVersion.Style.Add(HtmlTextWriterStyle.Left, "20px")
        Dim xlblShow As New Label
        xlblShow.Attributes("class") = "downlnkdetails"
        xlblShow.Text = "<h2>Show Older Versions<h2>"
        xShowVersion.Controls.Add(xlblShow)
        DivLeftVersion.Controls.Add(xShowVersion)

JS

        <script language="javascript" type="text/javascript">

                  $(document).ready(function() {

                  BindButtonClickEvent();

                  });
                  function BindButtonClickEvent() {
                      $('#<%= xlblShow.ClientID %>').click(function() {

                          alert('Hai');
                          return false;
                      });
                  }   
              </script>

But its Show Error. How to write event for asp label or any other controls in jquery?

am Using Asp.Net 2008

Sathish
  • 4,419
  • 4
  • 30
  • 59

2 Answers2

1

For dynamically added contents you need to use below code snippet

$(document).on('click', '#ID' , function(e){
      alert('clicked');
});
Ajay
  • 451
  • 2
  • 13
0

One of the easy ways of doing this, is to create a jQuery event handler that'll hook up to any future elements that are added to the DOM:

$( document ).on( "click", "h2", function() {
   alert( "Button Clicked!" )
});

You can read more about this in the jQuery.on() documentation. The 2nd parameter is a standard jQuery selector so could target by a class, id, element type etc.

Ian
  • 33,605
  • 26
  • 118
  • 198
  • 1
    At almost 18k rep you should know by now how to search for and vote to close as a duplicate. Delegated event handlers in jQuery have been covered more than enough times as it is, we don't need yet another answer on the topic. – Anthony Grist Feb 17 '16 at 13:44
  • @AnthonyGrist: Indeed I probably should have - that is my bad, sorry. There are however alternative answers for this question that are not true of the other questions (which don't feature the ASP.NET nature). I expected this answer to be an alternative and for someone to focus on a more ASP based answer using `ClientID` to be honest. I just don't know enough ASP to provide an answer of that form. – Ian Feb 17 '16 at 15:01