0

I am using RJS in my current project.

I have table rows with data and the last column contains a button, that binds javascript click function.

Now I have to do a AJAX and append newly created row to the table. It works fine. Here is the create.rjs template file.

page.insert_html(:bottom, "products", :partial => "product_row.html.erb", :locals => {:product => @product})

JS code:

jQuery(document).ready(function(){
  jQuery("button.add_color").click(function(){
    alert('ok');
  });
});

Everything works fine except the javascript click event is not working for newly created row.

Please help on how to keep bind the javascript events for newly added DOM by AJAX?

Venkat Ch
  • 1,168
  • 2
  • 17
  • 37

1 Answers1

1

I think you should use jQuery's .delegate method:

jQuery(document).ready(function(){
  jQuery('body').delegate('button.add_color', click, function(){
    alert('ok');
  });
});

From delegate's documentation:

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

dimakura
  • 7,575
  • 17
  • 36
  • I also found it working using `live` from [here](http://blog.revathskumar.com/2013/10/jquery-on-avoid-losing-event-binding-for-ajaxed-contents.html). I am not sure what is the efficient one. – Venkat Ch Sep 15 '15 at 20:55
  • @VenkatCh here's a good discussion http://stackoverflow.com/questions/4579117/jquery-live-vs-delegate you might find it useful – dimakura Sep 15 '15 at 20:58