显示是否基于对象值的表单隐藏字段,rails

Show if a form hidden field based on the value of the object, rails

我是一个学习型程序员,只知道rails中的ruby,对Javascript一无所知。我在 rails 上的 ruby 中有一个创建对象单元的表单。型号单位属于类别,而类别又属于 Product.So,您需要 select 产品作为单位,然后是类别。我遇到的问题是您可以 select 任何类别,但每个产品只有一些类别。所以我修改了我在互联网上找到的 js 代码,以便当您 selected 产品时,select 类别出现并仅显示该产品可用的类别。

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()

我现在遇到的问题是,当我编辑单元时,单元的产品 select 编辑正确,但类别被隐藏。只有当我重新 select 产品时,类别字段才会出现。有人可以帮我修改此 JS 代码,以便在编辑时根据单位产品 selected 显示类别字段吗?非常感谢!我添加了一些照片以更好地描述我的问题。

照片 1:编辑包含产品:bolsa 和类别:周末包的单元

照片 2:问题是,当我 select 编辑类别时,它显示所有类别,而不仅仅是产品类别。

照片 3:当我重新select 产品时,类别显示正确

我想修复代码,以便从一开始就正确显示类别。

根据答案,我这样解决了我的问题:

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()

尝试在更改回调中添加 $('#unit_category_id').parent().show(),然后再分配选项。