javascriptjqueryruby-on-railsformscoffeescript

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


I'm a learning programmer that only know Ruby on Rails and I know nothing of Javascript. I have a form in ruby on rails that creates a object Unit. The model Unit belong to Category that in turn belongs to Product.So in the form you need to select a product for the unit and then a category. The problem I had was you could select any Category but each product only have some categories. So I modified js code that I found on the internet so that when you selected Product, the select Category appeared and showed only the categories available for that product.

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

The problem I have now is that when I edit the unit, the unit's product is selected correctly but the category is hidden. Only when I reselect the product the category field appears. Can someone help me modify this JS code so that in the edit the category field appears based on the product selected based on the units product? Thanks a lot! I added some photos for better describing my problem.

Photo 1: Edit of a Unit with product: bolsa and category: weekend bag Edit of a Unit, product: Bolsa, category: Weekend Bag wit

Photo 2: The problem is that when I select category to edit it shows all categories and not just the product categories. enter image description here

Photo 3: When I reselect the product the categories are shown correctly

enter image description here

I want to fix the code so the categories are show correctly from the beginning.

Based on the Answer I fixed my problem like this:

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

Solution

  • Try adding $('#unit_category_id').parent().show() in the change callback, before assigning options.