【发布时间】:2020-03-09 10:46:20
【问题描述】:
我想知道如果选择了单选按钮,如何隐藏元素。
我有一个表单,如果选择了对应于account.kind == "person" 的单选按钮,我想同时显示first_name 和last_name 输入,否则它们应该被隐藏。
这里是Haml代码:
= simple_form_for(@account, html: { class: 'edit-form edit_account' }, wrapper: :edit_form) do |f|
%fieldset.large-2-col
%legend.hint
%span= t('views.accounts.profile.description')
.fields-block
= f.input :kind, as: :radio_buttons, wrapper_class: 'fields-group contact-type', item_wrapper_class: 'inline', item_wrapper_tag: 'div', collection: Account.kind.options, required: true, wrapper: :inline_radio
= f.input :first_name, autofocus: true, input_html: { data: { person: Account.human_attribute_name('first_name'), company: Account.human_attribute_name('company_name') } }
= f.input :last_name
以及可能相关或不相关的相关 CoffeeScript:
$("form input[name='account[kind]']").bind 'change', () ->
selected_value = $("input[name='account[kind]']:checked").val()
$("label[for='account_first_name']").html $('#account_first_name').data(selected_value)
$("#account_last_name").parents('.fields-group').toggleClass('hidden', selected_value != 'person')
$("#account_last_name").val('') if selected_value == 'company'
false
$("input[name='account[kind]']").trigger 'change' if $("input[name='account[kind]']").length > 0
【问题讨论】:
-
您需要创建一个事件来在选择单选按钮时隐藏输入的名字和姓氏。也许对“更改”事件执行 addEventListener ,并在必要时使用布尔标志。由于咖啡脚本和haml对我来说并不熟悉,我不会进一步评论,但这可能是您必须遵循的方向。
标签: ruby-on-rails ruby haml