javascriptjqueryruby-on-railsajaxrjs

Rails2: RJS - Javascript events are not working when on page updates remotely


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?


Solution

  • 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.