RoR:加载编辑页面时,是否根据用户选择显示/隐藏字段



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

我的表单字段

<%= 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 %>

application.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

下面的代码片段是您的解决方案的示例。如果有什么不合理的地方,请尝试执行,并在评论中告诉我。

当您从select下拉列表中更改选项时,它将调用选择器$("#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>

最新更新