开发者

jQuery UI DatePicker with nested_forms Gem

I've looked at this but this didn't solve my issue but it's the same circumstance. jQuery is loaded just fine.

Here's my 'nested_form':

<%= f.fields_for :events do |event_form| %>
<%= event_form.text_field :name %>
<%= event_form.text_field :date, :class => 'event_date' %>
<%= event_form.text_field :email %>
<%= event_form.开发者_开发知识库text_field :place %>
<%= event_form.link_to_remove "Remove Event", :class => "remove_task" %>
<% end %>

And here's the JS:

jQuery(document).ready(function($) {
  $('.event_date').each(function() {
    $(this).datepicker();
  });   
});

Lastly here's the html that's generated. You can see the jQuery UI adds it's class (hasDatepicker) for DatePicker:

<input class="event_date hasDatepicker" id="group_events_attributes_new_1317162040750_date" name="group[events_attributes][new_1317162040750][date]" size="30" type="text" style="border-top-left-radius: 5px 5px; border-top-right-radius: 5px 5px; border-bottom-left-radius: 5px 5px; border-bottom-right-radius: 5px 5px; ">

Any help would be greatly appreciated. Thanks!


Firstly, You can just write this for displaying the datepicker fields rendered from the beginning:

$(function() {
    $('.event_date').datepicker();
});

But for the fields created through javascript by nested_forms, you have to intercept the nested:fieldAdded event triggered by the form element after adding fields (see documentation here). You can accomplish it in this way:

$(function() {
    $('form').live('nested:fieldAdded', function(event) {
        $(event.field).find('.event_date').removeClass('hasDatepicker').datepicker();
    });
});

Note the removeClass('hasDatepicker'): without it, the datepicker fields created dinamically by javascript are not initialized correctly.


I'm doing the same thing in a form right now. Here's my example with jQuery 1.7.

(function ($) {
    var app = {}, opts = { dateFormat: 'yy-mm-dd' }, dateSelector = 'input.event_date:visible';
    app.init = function(){
        $(window).on('nested:fieldAdded', onFieldAdded);
        $(dateSelector).datepicker(opts);
    };
    function onFieldAdded(e) {
        e.field.find(dateSelector).datepicker(opts);
    }
    $(app.init);
    return app;
} (jQuery));

For older versions of jQuery, you would use the following in the init function.

$(window).bind('nested:fieldAdded', onFieldAdded);

What's nicer about what I'm doing, is less repetition (strings for selectors) and I don't call datepicker on hidden elements, so there's no need to call 'removeClass('hasDatepicker') on elements added through nested_forms.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜