rails - dynamic select menus within nested_form_fo

2019-04-13 04:34发布

I'm using the nested_form_for in the usual way but I want to add dynamic select menus to the nested children.

I have the following coffee script (adapted from the 'dynamic-select-menus' railscast)

jQuery ->
  $( ".controls-row" ).each ->
    $(this).bind "change", ->
      type = $('#expense_type :selected').text()
      if (type == "miles")
        $('#amount_currency').hide()
        $('#km_traveled').show()
      else 
        $('#amount_currency').show()
        $('#km_traveled').hide()

the problem with this code is that it will only work with the first nested element. I tried adding unique id's to each of the elements but that only works for existing elements. New elements are all clones of the 'blueprint' element and will all have the same ID.

Does anyone have a better way of implementing dynamic select menus within nested forms?

2条回答
Viruses.
2楼-- · 2019-04-13 04:47

Just use a regular expression to change the 'blueprints' id to something unique.

For example, if you are loading a partial you can use Javascript's replace to change the default ID.

聊天终结者
3楼-- · 2019-04-13 04:52

I soved it with this code:

jQuery ->
  $(document).on "nested:fieldAdded", (event) ->
    $( ".controls-row" ).each ->
        $(this).find('#expense_type').bind "change", ->
            type = $(this).parent().find('#expense_type :selected').text()
            if (type == "km")
                $(this).parent().find('#payment_method').addClass('hidden').hide()              
                $(this).parent().find('#amount_in_currency').addClass('hidden').hide()
                $(this).parent().find('#amount_currency').addClass('hidden').hide()
                $(this).parent().find('#km_traveled').removeClass('hidden').show()
            else 
                 $(this).parent().find('#payment_method').removeClass('hidden').show()
                 $(this).parent().find('#amount_currency').removeClass('hidden').show()
                 $(this).parent().find('#amount_in_currency').removeClass('hidden').show()
                 $(this).parent().find('#km_traveled').addClass('hidden').hide()
        $(this).find('#expense_type').trigger('change')

  $(document).trigger("nested:fieldAdded")
查看更多
登录 后发表回答