我试图在“skip_option”为“Yes”时显示“reason_for_skipping”字段,在“No”时隐藏。当选择“是”或“否”时,我希望动态播放“显示/隐藏”动作。不幸的是,只有在使用“更新选项”按钮将数据保存到数据库中之后才会发生这种情况。同样在Action“Start Assessments”下,当“Skip”为“No”且“reason_for_skipping”被隐藏时,需要显示,反之亦然。使用select_tag而不是f.select的此代码的先前版本按预期工作。我切换到表单版本,因为我需要将值保存在数据库中。
这是我的代码:
<%= simple_form_for(@option) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<h1>Select to Start or Skip Assessments</h1>
<br>
<table>
<thead>
<th>Action</th>
<th>Skip</th>
<th>Reason for skipping</th>
</thead>
<tbody>
<tr>
<td>
<%= link_to 'Start assessments', url_for(controller: :assessments, action: :index), id: 'start_assessment' %>
</td>
<td>
<%= f.select :skip_option, options_for_select([ "Yes", "No" ], :selected => f.object.skip_option), onchange: "reason_picker()" %>
</td>
<td>
<%= f.text_field :reason_for_skipping, id: 'reason_for_skipping' %>
</td>
</tr>
</tbody>
</table>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
<script type="text/javascript">
$(document).ready (
window.reason_picker = function () {
var selected = document.getElementById("option_skip_option").value;
if (selected == "Yes") {
$("#reason_for_skipping").show();
$("#start_assessment").hide();
}
else if (selected == "No"){
$("#reason_for_skipping").hide();
$("#start_assessment").show();
}
}
);
</script>
不确定我在这里缺少什么?
答案 0 :(得分:1)
select
helper有两个选项哈希值,html选项的哈希值是 second ,所以你要做的就是传递空哈希作为第一个选项。
f.select :skip_option, options_for_select([ "Yes", "No" ], :selected => f.object.skip_option), {}, onchange: "reason_picker()"