How do I connect jQuery Datepicker to my Ruby on Rails form?

前端 未结 7 2246
谎友^
谎友^ 2020-12-13 18:22

I\'m trying to use the jQuery Datepicker to set a date field in my Ruby on Rails form, but I can\'t work out how to do it. Can someone point me in the right direction?

7条回答
  •  有刺的猬
    2020-12-13 19:00

    Update for Rails 5.x

    Step 1. Install the jquery-ui-rails gem

    # gemfile
    gem 'jquery-ui-rails'
    
    # app/assets/javascripts/application.js
    //= require jquery-ui/widgets/datepicker
    
    # app/assets/stylesheets/application.css
    *= require jquery-ui/datepicker
    

    Step 2. Assuming you have a resource called Event with a date or datetime field called :start, then in the form make the :start field a text field.

    # app/views/events/_form.html.erb
    <%= f.label :start, 'Start Date' %>
    <%= f.text_field :start %>
    

    Step 3. Add Javascript (in CoffeeScript syntax here). Line1) If you have Turbolinks enabled (Turbolinks speeds up Rails page loads when you click on a link by loading it with AJAX) you need to add a wrapper or the JavaScript function won't load when you navigate to the page from an internal link.

    Line2) You are targeting the element id in your form. Rails automatically assigns an id to the form input by combining the Model name and field name.

    Line3) You need to set the dateFormat because jQuery-UI and Rails use different default date formats.

    # app/assets/javascripts/event.coffee
    $(document).on 'turbolinks:load', ->
      $('#event_start').datepicker
        dateFormat: 'yy-mm-dd'
    

    For Rails 4 everything is the same except the first line in the JavaScript (or CoffeeScript) file. The wrapper to load the JavaScript when Turbolinks is enabled in Rails 4 is:

    $(document).on "page:change", ->
    

提交回复
热议问题