Add Event To Dynamically Added Control

Introduction

Sometimes in real world project we require that we can add html control dynamically to after page successfully rendered on browser. We also require to perform certain task such as register event based on requirement.

In this article we learn about how we can register event on html control which was added dynamically using jquery.

Two implement this type of demo first of all we require jQuery library you can download from Here.

Html Snippet:
<div class="container">
<div class="body-container">
<input id="btnNew" type="button" value="Add New Button" />
<ul class="parent-ul"></ul>
</div>
</div>
JavaScript Snippet:
        $(function () {
            console.log("DOM is READy");
            // button handler which is responsible for 
            //adding new html control
           $('#btnNew').click(function () {
            var cnt = $('.parent-ul .item').length;
            $('.parent-ul').append($("<li/>").addClass('item').text("Item"+(cnt+1)));
       });
            //Below method register click event on dynamically
          // added control
            $('.parent-ul').on('click', '.item', function () {
                console.log($(this));
            });
             //Below commented code also worked
             //$(document).on('click', '.item', function () {
             //  console.log($(this));
             //});
     });

You can test above code on jsfiddle link
As per above code we are adding new list item dynamically as child element of unorder list '.parent-ul'.

To achieve this we have register click event on all child element of specific parent element(here parent-ul class) as per the above code.

In some scenario we didn't know exact parent element or have multiple parent with same type of child control, in that type of condition below code work perfectly as document (DOM) is parent of all element rendered on browser so we can attach any event or perform some specific tasks for control which are added dynamically in page.
             
             //Below commented code also worked
             $(document).on('click', '.item', function () {
               console.log($(this));
             });

Conclusion

In this article we have learn about how we can access or register event on dynamically added control on page using jquery.

Comments

Post a Comment

Popular posts from this blog

Dynamic Query in LINQ using Predicate Builder

Common Asp.Net Tips and Tricks

Payumoney Integration With Asp.Net