简体   繁体   English

有条件地在Ruby on Rails表单上显示字段

[英]Conditionally show fields on Ruby on Rails form

I have a Ruby on Rails app using Bootstrap for styling. 我有一个使用Bootstrap进行样式设计的Ruby on Rails应用程序。 This is a snippet from a form and I want to make a field visible once the non-blank value from the previous field is selected. 这是表单的摘要,一旦选择了上一个字段的非空白值,我想使该字段可见。 Thus, once non-blank 'criteria' is selected, I want to make the 'criteria_reason' field visible. 因此,一旦选择了非空白的“条件”,我想使“ criteria_reason”字段可见。 How can this code be fixed? 该代码如何固定?

<%= f.select :criteria, ['', 'Yes', 'No', 'Maybe'] %>

<%= f.text_field :criteria_reason, class:"form-control", placeholder:'Reason',
      style:"#{'display:none' if :criteria == ''}" %>

Thanks! 谢谢!

you can use javascript to make it visible on invisible when you click drop-down. 您可以使用JavaScript在单击下拉菜单时将其显示为不可见。

<script type="text/javascript">
  $(function () {
    $("#category_category_id").change(function () {
        var category = $(this).val();
        if (category != "") {
          $("#category_criteria_reason").show();
        } else {
          $("#category_criteria_reason").hide();
        }
    });

  });
</script>

change category_ with you own form class. 使用您自己的表单类更改category_ Then, you can change you default code into 然后,您可以将默认代码更改为

<%= f.text_field :criteria_reason, class:"form-control", placeholder:'Reason',
      style:"#{'display:none' if f.object.criteria == ''}" %>

by calling form_for @object do |f| 通过调用form_for @object do |f| you are passing @object into a ActionView::FormBuilder . 您将@object传递到ActionView::FormBuilder In f you can access the related object by calling f.object f您可以通过调用f.object来访问相关对象

so in this case you need to do 所以在这种情况下,您需要

<%= f.text_field :criteria_reason, class:"form-control", placeholder:'Reason',
      style:"#{'display:none' if f.object.criteria == ''}" %>

see http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html 参见http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM