div 显示/隐藏 UJS,记住表单包含错误和渲染(操作::新)时的状态



使用"form_for"为"人员"模型构建人员。这是UJS在复选框单击时显示和隐藏div。

人.js

  window.onload = function() {
    $('#is_student_chkbx').click(function() {
      return $('#student_properties').toggle();
    });
    return true;
  };

生成页面人员/新

...
<input id="is_student_chkbx" name="person[role_attributes][is_student]" type="checkbox" value="true" />
<div id='student_properties' style='display:none;'>
  <p>Test text</p>
</div>
...

people_controller.rb

class PeopleController < ApplicationController
  def new
    @person = Person.new
    @person.build_role
  end
  def create
    @person = Person.new(params[:person])
    ...
    @person.save ? redirect_to(person_path(@person)) : render(action: :new)
  end
end

但是有一个问题。当表单包含错误(例如"名称不能为空",因为模型中的验证)时,会发生render(action: :new)但即使选中'student_properties'div 也不可见'is_student_chkbx'。因此,当我再次单击'is_student_chkbx' ->复选框未选中'student_properties'但会显示div。

那么如何记住这个div的状态呢?

我试图向window.onload添加if ($('#is_student_chkbx').is(':checked')) {$('#student_properties').show();},但它没有发生在render(action: :new)

为了让它工作,我使用了(感谢 rb512,他指出了我的注意力):

<div id='student_properties' style='display:<%= @person.role.is_student ? 'block' : 'none' %>;'>

而不是:

<div id='student_properties' style='display:none;'>

但更好的方法是使用 CSS 类:

.hidden {
  display:none;
}

然后目标字符串将如下所示:

<div class='your_other_class <%= 'hidden' unless @person.role.is_student %>' id='student_properties'>

在新操作中添加以下内容:
更新:错过了报价
@person.role.is_student = false || params['is_student_chkbx']

最新更新