views:

22

answers:

2

I have a table with and id of foo and I want to add rows dynamically that have a button that do something. How can I assign the listeners for the buttons dynamically using JQuery?

Thanks

+2  A: 

You can use the bind method to assign event listeners if your buttons are already present or use the live or delegate methods if the buttons are generated dynamically.

Update:

Try with live() method:

$('.edit').live('click', function(){
  // your code here...
});
Sarfraz
I tried using bind. I gave my button a class of edit and I selected based on $('.edit'). Am I doing something wrong if it's in a table?
2Real
@2Real: See my updated answer please.
Sarfraz
Ok it works but rather than run the function once it runs it more than once. Is that supposed to happen? Is there a way I can just make the function run once?
2Real
@2Real: Have a look at jQuery's `one` method: http://api.jquery.com/one/
Sarfraz
I tried using one and it didn't do anything.
2Real
I figured what was going wrong. Thanks for the help!
2Real
A: 

you can assign class to dynamically added buttons and write something like if class is adder

$(function(){
   $(".adder").live("click",function(){
        //do something
});
});
Muhammad Adeel Zahid