仅当用户选择rails表单中的特定选项时,如何显示字段

问题描述 投票:0回答:1

在我的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 %>
ruby-on-rails forms if-statement
1个回答
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是在html中转换erb文件时由rails生成的id自动,因此它可以在您的情况下有所不同。 (只需登录控制台)
  • 如果用户更改了他的第一个选择,请不要忘记addClass('hidden')
© www.soinside.com 2019 - 2024. All rights reserved.