Rails - 动态更改表单中的选项

时间:2015-05-05 03:22:01

标签: javascript ruby-on-rails ruby forms form-for

我目前有一个创建clinicians的表单。在此表单中,我希望获得clinician_type的下拉列表,用户可以在physiciannurseother之间进行选择。根据用户的选择,表单将适应允许他们为Speciality选择physician或为Occupation选择nurse

我尝试实施23459948的答案,并将其调整为有三个选项,但我不知道javascript,我无法让它工作。

每个Clinician belongs_to

:occupation :speciality OccupationSpeciality以及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>

后面跟着physiciansnurses的更多选项相同。

目前Speciality显示所有选项,Occupation仅在选择nurse时出现(按照预期)。

我真的很感激任何建议,根据下拉选择制作适合的表格。我已尝试实施17525724的答案,但还没有让它发挥作用。

0 个答案:

没有答案