Search code examples
jqueryruby-on-railscoffeescriptrubygemsturbolinks

Ruby On Rails: jQuery datepicker only works when refresh page


The problem I am having is that when I navigate through the form page and I click on the date_sent on my text field, jQuery is supposed to pop-up a datepicker. However, I get nothing at first, but when I refresh the page it works.

I am almost sure that my problem is with turbolinks, because I assume that my JavaScript does not get loaded because of turbolinks. However, I do not want to remove turbolinks because my page renders slow without it. How can I make this work?

application.js

//= require jquery
//= require jquery-ui/datepicker
//= require jquery_ujs
//= require bootstrap-sprockets
//= require cocoon
//= require turbolinks
//= require_tree .

application.scss

 *= require_self
 *= require jquery-ui/datepicker
 *= require_tree .
 */

@import 'bootstrap-sprockets';
@import 'bootstrap';
@import 'sites';

form.coffee

jQuery ->
    $('#send_date').datepicker()

form.html.erb

<div class="form-group" >
      <%= f.label :date_sent, class: 'control-label' %><br>
      <%= f.text_field :date_sent, id: 'send_date' %>
</div>

Solution

  • Did you try turbolinks:load event ?

    $(document).on "turbolinks:load", -> 
    

    instead:

    $(document).ready, ->