【问题标题】:RoR: Showing/hiding fields based on user selection when loading edit page?RoR:加载编辑页面时根据用户选择显示/隐藏字段?
【发布时间】:2021-08-02 23:29:57
【问题描述】:

我有一个下拉列表,用户在其中进行选择,然后显示部分中的相应字段供他们完成。

我的表单域

    <%= f.simple_fields_for :security do |security| %>
      <%= security.label :security_type %>
      <%= security.select :property_type, Security.property_types.keys, {}, class: 'project-dropdown- 
      width', id: "security" %>
                         
      <div id="property-fields">
        <%= render partial: "project_steps/security_partials/property", security: @security, locals: { security: security } %> 
      </div>
                                 
      <div id="other-fields" style="display: none;">
        <%= render partial: "project_steps/security_partials/land", security: @security, locals: { security: security } %>
      </div>
    <% end %>

应用程序.js

document.addEventListener('turbolinks:load', () => {
  const element = document.getElementById('security');
    if (element) {
      $('#security').change((e) => {
        if (e.target.value == 'other') {
          $('#property-fields').eq(0).hide();
          $('#other-fields').eq(0).fadeIn();
        }
        else {
          $('#property-fields').eq(0).fadeIn();
          $('#other-fields').eq(0).hide();
        }  
     });
   }
});

这适用于根据用户在表单中单击的选项显示和隐藏必填字段。但是,当用户保存、前进,然后再次返回页面(进行编辑)时,所选选项是正确的,但如果他们在此示例中选择了“其他”,则字段不是正确的。它会改为显示“属性”字段。

如果用户返回页面进行编辑,我如何才能根据用户选择的选项显示正确的字段?

ty

【问题讨论】:

  • 您只在更改事件上运行逻辑,所以在用户更改任何内容之前没有什么会导致此逻辑运行,对吧?你需要让它在更改和初始加载时都运行

标签: javascript jquery ruby-on-rails show-hide


【解决方案1】:

下面的代码 sn-p 您的解决方案示例。请尝试执行该操作,如果有任何不妥之处,请在评论中告诉我。

当您从选择下拉菜单中更改选项时,它将在选择器$("#security") 上调用.change 事件。

同样的方式,你可以通过这行 jQuery 代码$("#security").val()获得当前选定值的值

所以您只需要编辑页面上的预选值,您将拥有基于该值的字段。

// document.addEventListener('turbolinks:load', () => {
//   const element = document.getElementById('security');
//   if (element) {

      $('#security').change((e) => {
        showFields(e.target.value)
      });

      showFields($('#security').val());

      function showFields(val) {
        if (val == 'other') {
          $('#property-fields').eq(0).hide();
          $('#other-fields').eq(0).fadeIn();
        }
        else {
          $('#property-fields').eq(0).fadeIn();
          $('#other-fields').eq(0).hide();
        }  
      }

//   }
// });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="security">
  <option value="propertis">Properties</option>
  <option value="other" selected>other</option>
</select>
<div id="property-fields">
   These are property-fields
</div>                      
<div id="other-fields" style="display: none;">
   These are other-fields
</div>

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 2011-06-26
    • 2019-10-19
    • 1970-01-01
    相关资源
    最近更新 更多