在多行数据中,日期选择器只改变第一行数据

In multiple rows of data, the datepicker only changes the first row of data

我似乎对 jQuery UI 日期选择器有一个奇怪的问题。如果它位于包含多行数据的 table 中,即使用户单击更下方的行,它也会更改第一行中的日期。

观点:

= form_tag bar_foo_path(@bar.id, @foo.id), id: "order-costs", method: :patch do |f|
  %table.table.table-bordered.table-select
    - @all_foos.each do |foo|
      %tr
        = fields_for "all_foos[]", foo do |p|
          %td= p.text_field :cf_date, value: formatted_date(foo.cf_date), maxlength: '10', placeholder: 'yyyy-mm-dd', class: 'save-data datepicker'

JavaScript:

$(document).ready(function() {
  $(".datepicker").datepicker({
    dateFormat: "yy-mm-dd"
  }).prop('readonly', true);
});

奇怪的是它只影响单独的行。如果它连续有多个日期选择器,则该行中的日期选择器正常工作。它只影响其他行中的类似数据。

想法?

我已经看过这个答案了:

Datepicker only changes date in first row of table。这涉及将日期选择器添加到呈现页面后添加的行。

我已经弄清楚这个问题了。当您将 fields_fortext_field 一起使用时,它将根据 fields_fortext_field 对象名称生成输入名称。在我的例子中,因为我让 fields_for 使用 all_foos[],它生成了一个名称为 all_foos__cf_date 的输入。该类型的所有输入都有该名称,而 datepicker 只是用该名称填充第一个输入。

我通过将 all_foos[] 更改为 all_foos[#{foo.key}] 来解决此问题。

你不能用...

f.fields_for :all_foos do |p|
  p.text_field(....)

通常它应该创建像 all_foos_0_cf_date, all_foos_1_cf_date

这样的输入