在我的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 %>
答案 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')