【发布时间】:2015-05-05 03:22:00
【问题描述】:
我目前有一个创建clinicians 的表单。在此表单上,我希望有一个clinician_type 的下拉列表,用户可以在physician、nurse 和other 之间进行选择。根据用户的选择,表单将进行调整,以允许他们选择Speciality 为physician 或Occupation 为nurse。
我尝试实现23459948 的答案并将其调整为具有三个选项,但我不知道 javascript,我无法让它工作。
Clinicianbelongs_to:occupation和:speciality和Occupation和Speciality每个has_many:clinicians。
我在表单中实现它的代码如下所示:
<%= form_for @clinician do |form| %>
Type of new clinician: <select id="clinician_type">
<option value="physician">Physician</option>
<option value="nurse">Nurse</option>
<option value="other">Other</option>
</select><br />
<span id="webname">
<div class="form-group">
<%= form.label :speciality_id %>
<%= form.collection_select :speciality_id, Speciality.all, :id, :name, { include_blank: true }, class: "form-control" %>
</div>
</span>
<script>
document.getElementById("clinician_type").onchange = function () {
if (document.getElementById("clinician_type").options[document.getElementById("clinician_type").selectedIndex].value == "physician")
document.getElementById("webname").style.display = "block";
else
document.getElementById("webname").style.display = "none";
}
</script>
<span id="webname2">
<div class="form-group">
<%= form.label :occupation_id %>
<%= form.collection_select :occupation_id, Occupation.all, :id, :name, { include_blank: true }, class: "form-control" %>
</div>
</span>
<script>
document.getElementById("clinician_type").onchange = function () {
if (document.getElementById("clinician_type").options[document.getElementById("clinician_type").selectedIndex].value == "nurse")
document.getElementById("webname2").style.display = "block";
else
document.getElementById("webname2").style.display = "none";
}
</script>
后面还有更多与physicians 和nurses 相同的选项。
目前Speciality 显示在所有选项中,而Occupation 仅在选择nurse 时才会出现(应该如此)。
对于制作根据下拉选择进行调整的表单的任何建议,我将不胜感激。我已经尝试实现17525724 的答案,但也没有得到它的工作。
【问题讨论】:
-
您目前的障碍到底是什么?其他下拉菜单不显示? Rails 错误?JS 错误?
-
您的问题与前端逻辑有关。这是因为一旦页面从服务器提供,它只是纯文本 HTML/CSS。那么,在这种情况下我会怎么做呢?我会在一个视图中渲染每个
form,并在 JavaScript 的帮助下为每个场景执行逻辑。knockout.js擅长处理这类问题。在下面的链接中有一个解决这个问题的例子knockoutjs.com/documentation/if-binding.html -
目前
Speciality显示所有选项,Occupation仅在选择nurse时出现(应该如此) -
@yeyo 我无法让
knockout.js工作。我有`这是一条消息。令人惊讶。` 我已将knockout-3.3.0.js添加到我的资产和application.js但没有任何功能 -
@Skiapex 我建议您在单独的文件夹/文件中复制淘汰赛页面的示例,以便在使用 rails 之前考虑它是否适合您的需求。也就是说,检查浏览器控制台的内容,可能有问题。例如,如果您使用的是 Rails,那么这行代码
<script type='text/javascript' src='knockout-3.3.0.js'>可能是问题的原因,因为这不是您通常加载从 Rails 提供的资产的方式。
标签: javascript ruby-on-rails ruby forms form-for