Rails上的Bootstrap Date Range Picker 4

时间:2015-10-29 00:04:13

标签: jquery ruby-on-rails-4 daterangepicker

我在Rails 4应用程序中添加了Bootstrap Date Range Picker,我遇到了问题。

情况:

我的代码看起来如何:

// Script
$(function() {
    $('.datepicker').datepicker({
            language: "de-DE"
    });
    $('.daterange').daterangepicker({
            'startDate': false,
            'endDate': false,
            'minDate': setDate(),
            'autoApply': true,
            "opens": "center",
            "locale": {
                "format": "DD.MM.YYYY",
                "separator": " - ",
                "daysOfWeek": ["So","Mo","Di", "Mi", "Do", "Fr", "Sa"],
                "monthNames": ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
                "firstDay": 1
            }
        },
        function(start, end, label) {
            $("#booking_start_date").val(start.format("DD.MM.YYYY"));
            $("#booking_end_date").val(end.format("DD.MM.YYYY"));

    });

//View
<%= text_field_tag 'date', nil, class: 'form-control daterange' %>
<%= f.input :start_date, as: :hidden %>
<%= f.input :end_date, as: :hidden %>

所以它应该做的是调用text_field上的daterangepicker并将所选值传递给隐藏字段,其中开始日期和结束日期被传递给控制器​​以进行保存。

问题:

问题在于,当我加载页面时,text_field内部始终存在相同的值,并且它始终是当前日期(例如今天:2015年10月29日 - 2015年10月29日)。显然,该字段应该为空以创建新的objekt,并且应该显示用于编辑现有对象的属性的当前值。所以我尝试添加一些jquery,它实际上没有做任何事情。

解决方案(不工作):

$(document).ready(function(){
    var start = $("#booking_start_date").val();
    var end = $("#booking_end_date").val();
    if (start != '' && end != '') {
        $('.daterange').val(start + "-" + end);
    } else {
        $('.daterange').val("");
    }
});

所以我想如果我从隐藏字段中捕获值并将它们放在一起并将结果字符串传递给text_field它应该可以工作。如果隐藏字段中没有值,则应显示空字符串。但正如所说,它没有做任何事情。如果我通过一些警报测试我的功能,则会给我正确的值。但text_field仍然显示与没有新功能相同的事情。

那么有什么想法吗?

1 个答案:

答案 0 :(得分:0)

I encountered a similar problem, and my first solution was to "cheat" a little; since daterangepicker will pick up the initial value from the form input, I filled it in server-side;

%input.daterange{type: "text", name: "date_range_picker_app_per", value: "#{app_per.start_on} - #{app_per.end_on}"}

The trick here is to ensure that your date formats are aligned; that is, daterangepicker needs to know what format Rails will put into that field. Your use of the locale option was what I used to make daterangepicker understand Rails's default date format.

This approach did expose a problem, though: what if start_on and end_on aren't set? To cover that case, I moved the generation of the range initial value to a helper method:

def range_initial_value(thingy)
  if thingy.start_on.present?
    "#{thingy.start_on} - #{thingy.end_on}"
  else
    ""
  end
end

Then I call the helper method in the HAML above. That satisfies daterangepicker since it won't receive " - " as an initial value.

Mine works now, and also works with an arbitrary number of date range pickers, so I'm happy.