Rails:有条件显示/隐藏表单字段的最佳方法? [英] Rails: Best way to conditionally show/hide a form field?

查看:94
本文介绍了Rails:有条件显示/隐藏表单字段的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型文档,该模型具有属性种类上下文. Kind是用作枚举的整数(使用出色的active_enum gem).上下文仅适用于类型为'2'的文档,即,如果文档不是2的任何类型,则 context 将为空白.

I have a model Document which has attributes kind and context. Kind is an integer that's used as as enum (using the excellent active_enum gem). Context only applies to documents of kind '2', i.e. if a document is any kind other than 2, context will be blank.

因此在表单页面中创建一个新文档,我有一个<select>来选择种类,以及一个用于上下文的文本区域,该区域最初是隐藏的:

So in the form page to create a new Document, I have a <select> to choose the kind, and a textarea for the context, which is initially hidden:

<%= form_for @document do |f| %>

  ...  

  <%= f.text_area :context, placeholder: 'Context', style: 'display:none' %>

  <%= f.select :kind, Document.active_enum_for(:kind).to_select %>

  ...

<% end %>

然后在绑定到下拉列表中的change()事件的函数中,使用jQuery的show()和hide()方法显示和隐藏文本区域.

And the textarea is shown and hidden using jQuery's show() and hide() methods in a function that's bound to the change() event on the dropdown.

到目前为止,太好了.但是在文档的 edit 页面上,我不希望在初始页面加载时始终隐藏上下文文本区域 ,因为我们可能正在编辑 2 .因此,如果我们正在编辑类型2的文档,则希望文本区域最初显示,但在其他情况下则隐藏.

So far, so good. But on the edit page for documents, I don't want the context textarea to always be hidden on the initial page load, because we may be editing a document of kind 2. So I want the textarea to initially be shown if we're editing a document of kind 2, but hidden in other cases.

这就是我现在拥有的:

<% if @document.kind == 2 %>
  <%= f.text_area :context, placeholder: 'Context' %>
<% else %>
  <%= f.text_area :context, placeholder: 'Context', style: 'display:none' %>
<% end %>

没有更好的方法吗?这对我来说有点罗and和多余;没办法,我只能打一个电话给f.text_area并有条件地包含style:选项吗?

Is there not a better way of doing this? This feels a bit wordy and redundant to me; is there no way I can just have one call to f.text_area and include the style: option conditionally?

还是我想得太多?

推荐答案

使用此方法:

  <%= f.text_area :context, placeholder: 'Context', style: "#{'display:none' if @document.kind == 2}" %>

或为此添加一个CSS类,

or you can add a css class for this,

display-none{
  display:none;
}

<%= f.text_area :context, placeholder: 'Context', class: "#{'display-none' if @document.kind == 2}" %>

谢谢

这篇关于Rails:有条件显示/隐藏表单字段的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆