0

I have a rails 4 application that uses turbo links and jquery.turbolinks. It also uses the jQuery date picker plugin.

I am using Ryan Bates' technique for adding/editing multiple models in one form, from Railscast episode #196 Nested Model Form.

In my case, I am adding/editing people associated with a household. The person_fields partial includes a birthdate field that 'attempts' to use the date picker (a string input with class="datepicker"), but it doesn't work, the datepicker doesn't appear when I click on the field with a class of '.datepicker'.

With other forms that are loaded with the page, the datepicker works fine. But for this form that is added dynamically with this code, the datepicker doesn't appear.

Here's the code for the link that inserts the partial:

  def link_to_add_fields(name, f, association)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
      render(association.to_s.singularize + "_fields", f: builder)
    end
  link_to(name, '#', class: "add_fields small round button success", data: {id: id, fields: fields.gsub("\n", "")})
 end

And the coffee script for inserting the partial:

$('form').on 'click', '.add_fields', (event) ->
  time = new Date().getTime()
  regexp = new RegExp($(this).data('id'), 'g')
  $(this).before($(this).data('fields').replace(regexp, time))
  event.preventDefault()

And the coffee script for the date picker:

$('.datepicker').datepicker()

Any help is much appreciated.

--- UPDATE ---

Thanks to Billy Monk's suggestion, the code to add fields now looks like this:

$('form').on 'click', '.add_fields', (event) ->
  time = new Date().getTime()
  regexp = new RegExp($(this).data('id'), 'g')
  $(this).before($(this).data('fields').replace(regexp, time))
  event.preventDefault()
  $('.datepicker').datepicker()

And it works! Much appreciated! Will accept the answer as soon as I'm allowed.

4

1 回答 1

2

在添加新字段的 JavaScript 函数中,在添加新字段后添加 $('.datepicker').datepicker()。日期选择器不会自动绑定到新添加的元素。

于 2013-02-15T21:36:45.490 回答