jQuery UI datepicker with foundation and form_tag

2019-09-08 08:18发布

问题:

I'm a beginner with jQuery and I'm trying to implement a datepicker. I have the jquery-ui-rails gem in my Gemfile. I'm using foundation and my form is:

<div class="row search-area">
  <%= form_tag search_index_path, method: :get do %>
  <div class="small-12 medium-1 large-1 columns search-field">
    <%= label_tag "From", nil, class: "right inline" %>
  </div>
  <div class="small-12 medium-2 large-2 columns search-field">
    <%= text_field_tag(:start_date, params[:start_date], :class => "date-field") %>
  </div>
  <div class="small-12 medium-1 large-1 columns search-field">
    <%= label_tag "To", nil, class: "right inline" %>
  </div>
  <div class="small-12 medium-2 large-2 columns search-field">
    <%= text_field_tag(:end_date, params[:end_date], :class => "date-field") %>
  </div>
  <div class="small-12 medium-1 large-1 columns search-field">
    <%= label_tag "Guests", nil, class: "right inline" %>
  </div>
  <div class="small-12 medium-2 large-2 columns search-field">
    <%= number_field(:number_of_guests, params[:number_of_guests], in: 1.0..20.0, step: 1.0) %>
  </div>
  <div class="small-12 medium-3 large-3 columns">
    <%= submit_tag "Search", name: nil, :class => "button" %>
  </div>
  <% end %>
</div>

In application.js I have:

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require foundation
//= require_tree .

$(function(){ $(document).foundation(); });

$(function() {
  $('.date-field').datepicker();
});

And in application.css.scss I have:

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

 @import "foundation_and_overrides";

The problem is that my text fields stay as text fields and no calendar pops up when I click on them.

After reading this question I tried stopping my server, running bundle update and then running bundle exec rake assets:precompile. This did not work.

I also tried to do a bit of digging around with the developer tools in Chrome. When I inspect the text-field element that's supposed to show the datepicker calendar and then click on 'sources' in developer tools, there's an 'app/jquery-ui' folder with a whole lot of css files. When I click on 'network' and reload the page the only javascript file I see is 'modernizr.self.js' which is apparently located in 'assets/vendor/'.

Does this mean that somehow the jquery-ui javascripts are not being compiled? If so how do I fix this?

After a bit of searching and further debugging - I think the problem might be with the asset pipeline and that application.js is not being seen at all.

回答1:

You may call datepicker, when document is ready. Like following code.

//= require jquery
//= require jquery_ujs
//= require jquery-ui/datepicker

$(document).ready(function() {
  $('.date-field').datepicker();
});