【问题标题】:Show if a form hidden field based on the value of the object, rails显示是否根据对象的值显示表单隐藏字段,rails
【发布时间】: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 代码,以便在编辑中根据单位产品选择的产品显示类别字段吗?非常感谢!为了更好地描述我的问题,我添加了一些照片。

图片 1:编辑产品:bolsa 和类别:周末包

照片 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


【解决方案1】:

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

【讨论】:

  • 感谢您的回答,很抱歉,我犯了一个错误,我所描述的是您建议的更改。我已经编辑了我的问题,我要添加一些图片
  • 哦,我明白了。那么product的默认选择值是Bolsa?问题是更改事件,如果您不将默认选定值更改为其他值,则不会触发其他类别组消失。您需要在更改回调中复制代码块并在回调外部添加副本,以便在第一时间正确设置类别。之后我还建议稍微重构一下代码
  • 产品 = $('#unit_product_id :selected').text() 选项 = $(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()
  • 这样的?
  • 这确实解决了这个问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-08-02
  • 2012-06-15
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
  • 1970-01-01
相关资源
最近更新 更多