2015-12-10 39 views
1

你好,我有一个窗体来创建一个产品。用户应该能够选择类别(例如T恤),然后T恤的所有尺寸(例如S,M,L)应该下降。用户可以输入他们每个尺寸的数量。选择类别,然后显示Category.sizes

JavaScript不为此工作。用户可以选择一个类别,但尺寸不会下降。任何人都能看到为什么我知道Rails,但我不知道JS。

当我检查我可以在HTML中看到的大小的视图。

这是我的看法

<%= javascript_include_tag "custom" %> 
<div class="container"> 
    <div class=“row”> 
    <div class="col-md-6 col-md-offset-3"> 
     <div class="panel panel-primary"> 
     <div class="panel-body"> 
      <%= simple_form_for @product_form, as: :product_form, url: products_path do |f| %> 
      <%= f.collection_select :category_id, @categories, :id, :name, include_blank: true, :prompt => "Select One Category" %> 
      <% @categories.each do |category| %> 
       <div class='sizes_container' id ='sizes_container_for_<%= category.id %>'> 
       <% category.sizes.each do |size| %> 
        <%= f.hidden_field :size_id, value: size.id %> 
        <%= size.title %> 
        <%= f.input :quantity %> 
       <% end %> 
       </div> 
      <% end %> 
      <%= f.input :title, label:"Title"%> 
      <%= f.input :price, label:"Price"%> 
      <%= f.input :description,label:"Description" %> 
      <%= f.input :tag_list,label:"Tags - Seperate tags using comma ','. 5 tags allowed per product" %> 
      <%= f.button :submit, "Create new product", class: "btn-lg btn-success" %> 
      <% end %> 
     </div> 
     </div> 
    </div> 
    </div> 
</div> 

这里是JS

this.products = { 
    updateCategory: function() { 
    var id = $('#product_category_id').val(); 
    $('.sizes_container').hide(); 
    $('#sizes_container_for_' + id).show(); 
    } 
}; 

$(function() { 
    products.updateCategory(); 
    $('#product_category_id').on('change', products.updateCategory); 
}); 

回答

1

首先,它是你,包括自定义的一个不好的迹象中的JavaScript功能视图:

<%= javascript_include_tag "custom" %> 

这应该在布局您正在使用:

#app/views/layouts/application.html.erb 
<%= javascript_include_tag :application, :custom %> 

虽然你所做的一切都没有错,但这是一个不好的做法(将你的JS全部分割为你的应用程序)。此外,如果你想真正有效的,你把你的代码到app/assets/javascripts/application.js文件本身:

#app/assets/javascripts/application.js 
$('document').on('change', 'select#product_category_id', function(e){ 
    var id = $(this).val(); 
    $('.sizes_container').hide(); 
    $('#sizes_container_for_' + id).show(); 
}); 

我也认为这是一个有点矫枉过正,以创建一个类此。你最好把代码放到一个函数中,就像上面那样。

-

上面应该工作,考虑到您的HTML是正确的。另外要注意的是,在Rails中,你应该总是绑定到DOM加载事件以某种方式:

$(document).ready(function(){ 
$(document).on("page:load" ... 

这主要是Turbolinks一个问题,但也比只用$(function...更好的做法。

相关问题