Search code examples
ruby-on-railsdatepickerturbolinks

Datepicker does not display the calendar


I have in my application a form where I can chose a date from a datepicker calendar. When I refresh my page, the datepicker calendar appears when clicking the form. This is the correct behaviour.

However when I reach the same page from another page using a link, the calendar does not appear after clicking the form. I have to refresh the page in order to make the calendar visible.

Here is my form page:

# app/views/reservations/_form.html.erb
...

      <div class="row reservations">
        <div class="span2 field">
          <%= f.label :mydate %><br />
          <%= f.text_field :mydate, class: "input-append date datepicker", value: Date.today.strftime('%d-%m-%Y') %>
        </div>
...

My javascript code:

# app/assets/javascripts/reservations.js.coffee
$ -> $('.date').datepicker({
    format: 'dd-mm-yyyy'
    autoclose: true
    todayHighlight: true
    language: 'fr'
});

And the Gemfile:

source 'https://rubygems.org'

ruby "2.0.0"

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0.beta1'
gem 'bootstrap-sass', '2.3.1.0'
gem 'bcrypt-ruby', '3.0.1'
gem 'protected_attributes'
gem 'will_paginate'
gem 'bootstrap-will_paginate'
gem 'bootstrap-datepicker-rails'
gem 'rails-i18n'

gem 'pg'

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 4.0.0.beta1'
  gem 'coffee-rails', '~> 4.0.0.beta1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', platforms: :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'

# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.0.1'

Solution

  • I was experiencing the same issue. This is a turbolinks problem.

    You can disable turbolinks at the source page that you're coming from by adding data-no-turbolink to the href or div, and this will get it working. i.e.

    <%= link_to "Create New Form", sampleform_path, 'data-no-turbolink' => true %> 
    

    See more details here, under the "Opting out of Turbolinks" section.

    [EDIT] I think the better solution is to call your document.ready code during the page:change event also in coffeescript. Here is the code you can use:

    $(document).on 'ready page:load', -> $('.date').datepicker({
        format: 'dd-mm-yyyy'
        autoclose: true
        todayHighlight: true
        language: 'fr'
    });