Rails 4 – 具有简单forms的依赖字段的JS

我想在Rails 4中创建一个应用程序。

我正在使用简单的表单forms,并且刚刚尝试使用gem’inpendent-fields-rails’来隐藏或显示基于主要问题的表单字段的子集问题。

我卡住了。

我已将gems添加到我的gem文件中:

gem 'dependent-fields-rails' gem 'underscore-rails' 

我已将我的application.js更新为:

 //= require dependent-fields //= require underscore 

我的表格有:

   
"Is this a project in which students may participate?", autofocus: true %>
"Is this a project students complete for credit towards course assessment?" %> "Is this project offered on a recurring basis?" %> "How often is this project repeated?", :collection => ["No current plans to repeat this project", "Each semester", "Each year"] %>
:date_picker, :label => "When do you want to get started?" %>
:date_picker, :label => "When do you expect to finish?" %>
:date_picker, :label => 'When are expressions of interest due?' %>
$('.datetimepicker').datetimepicker(); $(document).ready(function() { DependentFields.bind() });

我对javascript了解不多。

我不确定最终的脚本段是否必要,或者gem是否将它放入代码中。我不确定它是否应该在脚本标记内表达,我也不知道如何生效此要求(在依赖字段的gem页面上列出):

 "Be sure to include underscorejs and jquery in your page." 

你如何在页面中包含underscorejs和jQuery? 我把它们放在我的gem文件中。 这还不够,还是需要其他东西来完成这项工作?

目前,当我尝试这种forms时,没有任何东西被隐藏。 我已经尝试将真值交换为’是’,但这也没有任何区别。

 

谁能看到我出错的地方?

我认为您在定义单选按钮时跳过collection属性。

如果查看文档示例 ,您将看到它们使用collection来定义单选按钮的值。 然后,他们使用定义的值之一来设置data-radio-value属性。

试试这个让我知道:

 
<%= pdf.input :student_project, as: :radio_buttons, autofocus: true, :label => "Is this a project?", :collection => ['Yes', 'No'] %>
...

更新

如果查看此示例项目, application.js文件将以不同于您的顺序包含所需的库。 这可能是错误。

请注意,您需要以这种方式使用库:

 //= require dependent-fields //= require underscore 

虽然示例项目以这种方式需要库:

 //= require underscore //= require dependent-fields 

希望这有帮助!

 "Be sure to include underscorejs and jquery in your page." 

Rails会自动执行此操作。 它在设置时将jQuery添加到application.js文件中,因此如果你没有删除该行,我们可以跳转到第2步:

您需要将application.js脚本包含在您的页面中。 您可以在正在处理的视图中执行此操作,但如果您在应用程序的其他位置使用javascript,我建议您将javascript添加到应用程序的布局中,以便它将应用于使用该布局的所有页面。

默认情况下,该文件位于app/views/layouts/application.html.erb下。

必须将这行代码(或类似内容)添加到您的文件中,以便使用您的视图加载脚本:

<%= javascript_include_tag "application" %>

它将允许您访问所有的JavaScript代码。

编辑:

除此之外,我注意到你错过了显示字段的条款。 在依赖字段的文档中,它声明您必须指定您依赖的字段以及元素类的值,如下所示:

 
... fields ...

您应该将替换为这些字段所依赖的输入的id,并将替换为必须具有的相应值。