ghanshyam.mirani
ghanshyam.mirani

Reputation: 3101

creating an event of dynamically created an element in JQuery

I have table element

<table class="ActionMenu" id="tblActionMenu" cellpadding="3" cellspacing="3" >

John

 $('.ActionMenu tr').click(function (e) {
                alert("abcd");
     });

this works great.

now using javascript i have added table that has same class = "ActionMenu" but on click of tr it doesn't work.

how can i get the Message on Click event dynamically created table

Upvotes: 1

Views: 102

Answers (3)

ltiong_dbl
ltiong_dbl

Reputation: 3216

Check out example on delegated events on http://api.jquery.com/on/

$('#tblActionMenu').on("click", "tr", function(){
   //do something
});

Upvotes: 0

rafaelbiten
rafaelbiten

Reputation: 6240

You'll have to use "live" function... even better if you use "delegate" function.

It works like this:

$('.someClass').live('click',function(){}); //adds 'click evt' to every future .someClass inside the DOM

$('#someID').delegate('.someClass','click',function(){}); //adds 'click evt' to every future .someClass inside #someID

Search the jQuery api for more information or let me know if you need more help. Good luck!

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123438

Probably, when you defined your function the newer table does not exist yet. So assuming you're using latest jQuery Version (1.7.x) use event delegation and capture the event on a common parent (e.g. the body element)

 $('body').on("click", ".ActionMenu tr", function (e) {
      alert("abcd");
 });

Upvotes: 3

Related Questions