【发布时间】:2016-12-22 03:13:47
【问题描述】:
我是一名学习程序员,只知道 Rails 中的 ruby,对 Javascript 一无所知。我在 ruby on rails 中有一个创建对象单元的表单。模型单元属于类别,而类别又属于产品。因此,在表单中,您需要为单元选择一个产品,然后选择一个类别。我遇到的问题是您可以选择任何类别,但每个产品只有一些类别。所以我修改了我在互联网上找到的 js 代码,这样当你选择产品时,选择的类别就会出现,并且只显示该产品可用的类别。
jQuery ->
$('#unit_category_id').parent().hide()
categories = $('#unit_category_id').html()
$('#unit_product_id').change ->
product = $('#unit_product_id :selected').text()
options = $(categories).filter("optgroup[label='#{product}']").html()
if options
$('#unit_category_id').html(options)
$('#unit_category_id').parent().show()
else
$('#unit_category_id').empty()
$('#unit_category_id').parent().hide()
我现在的问题是,当我编辑单元时,单元的产品被正确选择但类别被隐藏。只有当我重新选择产品时,才会出现类别字段。有人可以帮我修改这个 JS 代码,以便在编辑中根据单位产品选择的产品显示类别字段吗?非常感谢!为了更好地描述我的问题,我添加了一些照片。
照片 2:问题是当我选择要编辑的类别时,它会显示所有类别,而不仅仅是产品类别。
照片 3:当我重新选择产品时,类别显示正确
我想修复代码,以便从一开始就正确显示类别。
根据答案,我这样解决了我的问题:
jQuery ->
$('#unit_category_id').parent().show()
categories = $('#unit_category_id').html()
product = $('#unit_product_id :selected').text()
options = $(categories).filter("optgroup[label='#{product}']").html()
if options
$('#unit_category_id').html(options)
$('#unit_category_id').parent().show()
else
$('#unit_category_id').empty()
$('#unit_category_id').parent().hide()
$('#unit_product_id').change ->
product = $('#unit_product_id :selected').text()
options = $(categories).filter("optgroup[label='#{product}']").html()
if options
$('#unit_category_id').html(options)
$('#unit_category_id').parent().show()
else
$('#unit_category_id').empty()
$('#unit_category_id').parent().hide()
【问题讨论】:
-
对于它的价值,那就是 CoffeeScript。
标签: javascript jquery ruby-on-rails forms coffeescript