Rails 4 + simple_form and jQuery UI. Datepicker is not working via turbolinks

前端 未结 3 871
栀梦
栀梦 2020-12-31 13:01

I have this form which calls datepicker:

...
<%= f.input :expiration_date, as: :datepicker, required: false %>
...

Simple_form wrappe

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-31 13:50

    I finally found a suitable fix:

    app/inputs/datepicker_input.rb is left the same, the wrapper works nice.

    assets/javascripts/application.js

    //= require jquery
    //= require jquery_ujs
    //= require turbolinks
    //= require bootstrap.js
    //= require_tree .
    
    $(document).on("page:load ready", function(){
        $("input.datepicker").datepicker();
    });
    

    Since :datepicker input type adds ".datepicker" class to rendered HTML, it's enough just to bind datepicker() to all elements with that class. It does the trick with the least amount of code.

    It's important to specify "input.datepicker" since the ".datepicker" class is added both to label and input tags.

    turbolinks throws a page:load event, so I've added handler for both cases - when the page loads with turbolinks, and when it loads from scratch (window refresh, link saved in favourites, etc)

    Now the following .html.erb is rendered as I expect:

    <%= f.input :expiration_date, as: :datepicker, required: false,
        :placeholder => 'Select date', input_html: {class: "form-control"},
        label: "Expiration date: " %>
    

    output:

提交回复
热议问题