ted
ted

Reputation: 187

Rails javascript calls after partial rendered

What's the right place to put javascript/coffeescript in Rails when working with partial being loaded via AJAX?

I would like to call:

$('.selector').datapicker() 

every time '_form' partial is loaded.

I can put this directly into the _form.html.erb partial and it would work like expected but I kinda feel like it's a wrong holder for js.

Upvotes: 2

Views: 880

Answers (2)

Nic
Nic

Reputation: 113

If you're using UJS data-remote to do the ajax, you can hook on to the ajax event that UJS makes. See here: https://github.com/rails/jquery-ujs/wiki/ajax

use ajax:complete to re-add datapicker to the element eg:

$('#submitted_form').on('ajax:complete', function(event, xhr, settings) {
  $('#date_field').datapicker();
});

...and then this would go in your assets/javascript folder.

Also check out this article: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

Upvotes: 0

CV-Gate
CV-Gate

Reputation: 1170

The 'right place' should be within the assets folder where all js scripts reside.

You can use:

$( document ).ajaxComplete(function( event,request, settings ) {
    $('.selector').datapicker();
});

Upvotes: 3

Related Questions