仅当用户在Rails表单中选择特定选项时如何显示字段

时间:2019-04-14 05:50:30

标签: ruby-on-rails forms if-statement

在我的rails应用程序中,我有一个表单,用户可以在其中选择一个类别,然后选择子类别,我想要的是,仅当用户选择了特定类别时才显示子类别。

<%= form_with(model: product, local: true) do |form| %>
  <% if product.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(product.errors.count, "error") %> prohibited this product from being saved:</h2>

      <ul>
      <% product.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<div class="form-style-5">
<form>
<fieldset>
<legend><span class="number">1</span> General Info</legend>
<%= form.text_field :name, id: :product_name, placeholder: "Add name of your product or service here" %>
<%= form.text_area :description, id: :product_description, placeholder: "Full Description" %>
<label for="job" style="color:#000;">Images:</label>
<%= form.file_field :image, id: :product_image %>
<%= form.file_field :imagetwo, id: :product_image %>
<%= form.file_field :imagethree, id: :product_image %>   
</fieldset>
<fieldset>
<legend><span class="number">2</span> Additional Info</legend>
<label for="job" style="color:#000;">Categories:</label>
    <%= form.select :category, ['Health Beauty & Babycare', 'Furniture & Homecare', 'Fashion', ' Grocery & Veg', 'Education', 'Business & Tax', 'Home Service & Repair', 'Personal Care'] %>


    <label for="job" style="color:#000;">Sub Categories:</label>
    <%= form.select :subcategory, ['Lips', 'Face', 'Nails', 'Kits', 'Tools',] %>
</fieldset>
<fieldset>
<legend><span class="number">3</span> Details</legend>
<%= form.text_field :price, id: :product_price, placeholder: "Price of your product/service (optional for services)" %>


</fieldset>
<div class="actions">
    <%= form.submit %>
  </div>
</form>
</div>
<% end %>

1 个答案:

答案 0 :(得分:0)

您需要使用JavaScript。

这里是一个示例:

<%= form_with(model: product, local: true) do |form| %>

<fieldset>
<legend><span class="number">2</span> Additional Info</legend>
<label for="job" style="color:#000;">Categories:</label>
    <%= form.select :category, ['Health Beauty & Babycare', 'Furniture & Homecare', 'Fashion', ' Grocery & Veg', 'Education', 'Business & Tax', 'Home Service & Repair', 'Personal Care'] %>

    <div id="subcategory" class="hidden">
      <label for="job" style="color:#000;">Sub Categories:</label>
      <%= form.select :subcategory, ['Lips', 'Face', 'Nails', 'Kits', 'Tools'] %>
    </div>
</fieldset>

<script language="javascript">
  $('#product_category').change(function(event){
    if($('#product_category').val() === 'Health Beauty & Babycare') {
      $('#subcategory').removeClass('hidden');
    }
  });
</script>
  • #product_category是Rails在html中转换erb文件时自动生成的ID,因此您的情况可能会有所不同。 (只需在控制台中检查)
  • 如果用户更改了他的第一选择,别忘了addClass('hidden')